c++ getline没有得到输入

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

感谢您的帮助,谢谢。

最佳答案

需要消耗换行符。

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

关于c++ getline没有得到输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990640/

相关文章:

javascript - 上传大文件并对其进行解析时出现 fatal error Node.js v10.15.1

c++ - 如何使用代码块和 gcc 创建预编译头文件

c - Libcurl 如何不显示所有这些信息

c++ - 在 QtCreator 中使用 cin

c++ - 试图避免在双点运算中舍入,无法超过双

c++ - 为什么 scanf 似乎跳过了输入?

c++ - 使用 cout 从 cin.get() 输出类型 int

c++ - Cin() 为用户预先键入 "y"

c++ - 为什么我不能使用集合作为 vector 变换操作的输出集合?

c++ - gtest 和 MinGW 联动