c ++ getline没有得到输入

c++ getline doesn't get the input

我正在尝试输入一行,然后输入一个整数,然后再输入一行,但是当最后一个 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;
}

感谢您的帮助,谢谢。

您需要消耗换行符。

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

对于 cin 之后的情况,您应该使用 cin.ignore() 而不是 cin.get() ,如下所示:

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