如何使用“获取”函数在C ++以前的输入? [英] How to use "gets" function in C++ after previous input?

查看:163
本文介绍了如何使用“获取”函数在C ++以前的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用 gets()函数输入数据,但是当程序执行到获得

  • c>,它忽略它。

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

    当我使用 gets()而没有之前的数据输入时,它会正常运行。

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

    如何解决此问题?

    推荐答案

    >

    cin >>a
    

    当您输入 a 并输入时,还有一个 \\\
    cin ,因此,当您使用 cin.getline() (str)
    ,它将读取该换行符。

    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.

    请尝试以下操作:

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

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

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

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

    这篇关于如何使用“获取”函数在C ++以前的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆