【发布时间】:2015-11-30 02:34:02
【问题描述】:
我正在尝试输入一行,然后输入一个整数,然后再输入一行,但是当最后一个 cin 获取该行并且我按 Enter 时,它会崩溃或随机输出到无穷大。怎么了?
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;
}
感谢您的帮助,谢谢。
【问题讨论】:
-
it crashes or outputs randomly我感觉你没有显示你正在使用的代码,因为上面的代码不可能崩溃甚至输出。在任何情况下,getline(cin, b);并没有按照您的想法执行,您的缓冲区中可能有一个从cin >> n1;遗留下来的换行符,所以getline(cin, b);读取该换行符,然后cin >> n2;尝试读取您期望的任何内容被读入b并且可能会失败。 -
不要将
getline与cin >>类型输入混用。它永远不会像你期望的那样工作。 -
它实际上并没有崩溃,而是输出随机文本。
-
对于这类问题,您应该复制并粘贴您的确切输入,因为您的代码将“工作”某些输入而不是其他输入。
标签: c++ codeblocks cin getline