简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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