简体   繁体   English

C ++ getline没有得到输入

[英]c++ getline doesn't get the input

i am trying to input a line and then an integer then a line again however when it the last cin gets the line it and i press enter it crashes or outputs randomly to the infinity. 我正在尝试输入一条线,然后输入一个整数,然后再输入一条线,但是当最后一个cin获得该行时,我按Enter键便会崩溃或将其随机输出到无穷大。 whats wrong? 怎么了?

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

I appreciate for your help, thanks. 感谢您的帮助,谢谢。

You need to consume the newline character. 您需要使用换行符。

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 will consume the newline for you. std::getline将为您使用换行符。

Here's example usage: 这是示例用法:

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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM