c ++ getline无法获得输入

时间:2015-11-30 02:34:03

标签: c++ codeblocks cin getline

我正在尝试输入一行然后再输入一个整数然后再输入一行但是当它最后一个cin得到该行时我按下输入它会崩溃或随机输出到无穷大。怎么了?

int main(){
    string a= "", b = "";
    int n1 = 0, n2 = 0;

    getline(cin, a);
    cin >> n1;

    //when i input the next like it outputs randomly without continuing with the next like why?
    getline(cin, b);

    //it doesn't let me to input here coz it's outputting some random strings.
    cin >> n2;
    return 0;
}

感谢您的帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

您需要使用换行符。

int main(){
    string a, b;
    int n1, n2;

    getline(cin, a);

    cin >> n1;
    cin.get(); // this will consume the newline
    getline(cin, b);

    cin >> n2;
    cin.get(); // this will consume the newline
}

std::getline将为您使用换行符。

以下是示例用法:

21:42 $ cat test.cc 
#include <iostream>
#include <string>

using namespace std;

int main(){
    string a, b;
    int n1, n2;

    getline(cin, a);

    cin >> n1;
    cin.get(); // this will consume the newline
    getline(cin, b);

    cin >> n2;
    cin.get(); // this will consume the newline

    std::cout << a << " " << b << " " << n1 << n2 << std::endl;
}
✔ ~ 
21:42 $ g++ test.cc
✔ ~ 
21:42 $ ./a.out 
hello
4
world
2
hello world 42

答案 1 :(得分:1)

对于cin之后的情况,您应该使用cin.ignore()而不是cin.get()这样:

cin.ignore(numeric_limits<streamsize>::max(), '\n');