C ++ getline没有得到输入 [英] c++ getline doesn't get the input
本文介绍了C ++ getline没有得到输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图输入一条线,然后输入一个整数,然后再输入一条线,但是当最后一个cin获得该行时,我按Enter键,它会崩溃或随机输出到无穷大.怎么了?
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;
}
感谢您的帮助,谢谢.
推荐答案
您需要使用换行符.
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没有得到输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文