问题
I tried to input data with gets()
function, but whenever program execution get to the the lien with the gets
, it ignores it.
When I use gets()
without previous data input, it runs properly. But when I use it after data input the problem happens.
Here's the code where it is used after previous data input (so in execution I can't input data to string):
int main() {
char str[255];
int a = 0;
cin >> a;
if(a == 1) {
gets(str);
cout << "\n" << str << endl;
}
}
How could I fix this?
NB: the same happens with cin.getline
回答1:
After
cin >>a
when you input a
and enter, there is also a \n
character left by cin
, therefore, when you use cin.getline()
or gets(str)
it will read that newline character.
try the following:
cin >>a;
cin.ignore(); //^^this is necessary
if(a==1){
gets(str);
}
You'd better use C++ way of reading input:
cin >> a;
cin.ignore();
string str;
if (a == 1)
{
getline(cin, str);
}
来源:https://stackoverflow.com/questions/16406333/how-to-use-gets-function-in-c-after-previous-input