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

删除回忆录丶 提交于 2019-12-22 14:52:32

问题


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

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