getting console input for Cstrings

Deadly 提交于 2019-12-24 09:14:48

问题


note: this is in C++ but using C-style strings

hello SO,

I'm working on an assignment and I need to get input from the console and save it to a cstring. Everything compiles fine, but when the program runs, it just skips over getting input from the user. So it will output: "Enter string to be inserted: " then skip the cin.getline function, then execute the next command.

Here's my header files, the declaration of the cstring, and the line of code I'm having trouble with.

#include "stdafx.h"
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
  char tempCString[500] = {};

//...code snipit...

  cout << "Enter string to be inserted: " << endl;
  cin.getline(tempCString, 500, '\n'); //I've also tried cin.getline(tempCString, 500);

//...end code snipit...

  return 0;
}

note: I can't use "cin >> tempCString" becaues it will only get the input up to the first space, I need to get input from the console of everything up to the newline.

Thank you


回答1:


Try clearing cin's buffer before getting new input:

#include <limits>

cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max());
cout << "Enter string to be inserted: " << endl;
cin.getline(tempCString, sizeof(tempCString), '\n');

See How do I flush the cin buffer?



来源:https://stackoverflow.com/questions/9755100/getting-console-input-for-cstrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!