问题
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