C++ 之前输入后如何在C++中使用“gets”函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16406333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:19:35  来源:igfitidea点击:

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

c++stringgets

提问by afr0ck

I tried to input data with gets()function, but whenever program execution get to the the lien with the gets, it ignores it.

我尝试使用gets()函数输入数据,但是每当程序执行到达带有 的留置权时gets,它都会忽略它。

When I use gets()without previous data input, it runs properly. But when I use it after data input the problem happens.

当我在gets()没有先前数据输入的情况下使用时,它运行正常。但是当我在数据输入后使用它时,问题发生了。

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

注意: cin.getline 也是如此

回答by taocp

After

cin >>a

when you input aand enter, there is also a \ncharacter left by cin, therefore, when you use cin.getline()or gets(str)it will read that newline character.

当您输入a和回车时,还有一个\n字符被留下cin,因此,当您使用cin.getline()or 时,gets(str)它会读取该换行符。

try the following:

尝试以下操作:

cin >>a;
cin.ignore(); //^^this is necessary
if(a==1){
    gets(str);
}

You'd better use C++ way of reading input:

你最好使用 C++ 读取输入的方式:

cin >> a;
cin.ignore();
string str;
if (a == 1)
{
   getline(cin, str);
}