在getline之前需要cin.get()(cin,string_name)

时间:2017-04-09 21:19:30

标签: c++ string cin

我有一个简单的程序来输出2个整数的和,双和连接2个字符串。这是我的代码可以正常工作:

int main() {
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";  
    // Declare second integer, double, and String variables.
    int i2;
    double d2;
    string s2;

    // Read and save an integer, double, and String to your variables.
    cin>>i2;
    cin>>d2;
    cin.get();
    getline(cin, s2);

    // Print the sum of both integer variables on a new line.
    cout<<i+i2<<endl;

    // Print the sum of the double variables on a new line.
    cout<< setprecision(1)<<fixed<<d+d2<<endl; 

    // Concatenate and print the String variables on a new line
    // The 's' variable above should be printed first.
    cout<<s+s2;
    return 0;
}

但是,如果我删除语句cin.get(),则不会发生字符串s2的输入。为什么会这样?

我认为这与流/输入缓冲区和getline(cin,)的内部编码有关。此外,当我使用cin.getline()时,程序会出错。

1 个答案:

答案 0 :(得分:-1)

尝试:

cin.ignore(); 

然后

getline(cin, s2);
cin.ignore();

这将刷新输入流。

相关问题