How to use "gets" function in C++ after previous input?

user2355950 picture user2355950 · May 6, 2013 · Viewed 27k times · Source

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

Answer

taocp picture taocp · May 6, 2013

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);
}