它可能不是一个问题,但我不知道什么错误。 我的第一个条目重复2日迭代STR1,距离那么同样的方式。 只有第一次迭代变好。
#include <iostream>
#include <string>
using namespace std;
int main () {
cout << " \n Enter two words. \n " ;
char c = 'y';
string str;
string str1;
while (c == 'y'){
getline(cin,str);
getline (cin,str1);
cout << " \n\n str : " << str << " str1 : " << str1 ;
cout << " \n Continue ? \n " ;
cin >> c;
}
return 0;
}
输出是:
Enter two words.
hello world
this is mr
str : hello world str1 : this is mr
Continue ?
y
hello world
str : str1 : hello world
Continue ?
n
加
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
你的后
cin >> c;
请看下面的输入:
dog
cat
y
owl
fish
n
如果我们检查是存在单独的输入流中的人物,我们会看到:
d o g \n c a t \n y \n o w l \n f i s h \n n \n
首次调用getline
消耗dog\n
; 第二消耗cat\n
,离开这个:
y \n o w l \n f i s h \n n \n
第一次调用cin >> c
仅消耗y
但没有后续的换行 ,离开这个:
\n o w l \n f i s h \n n \n
现在,有趣的开始:在接下来的通话过程中会发生什么getline
? 为什么它会读取到下一个新行,当然。 因此,要在下次调用getline
返回一个空行 ,离开owl...
输入流。
该解决方案,如我上面概述,是消耗(现在没用)输入线的其余部分。
由于抢说。
但另一种修复,看起来更好:
// change
char c = 'y';
....
while (c == 'y'){
....
cin >> c;
// Into
std::string c = "y";
....
while (c == "y"){
....
std::getline(cin, c);
当使用手动输入用户打交道,你应该小心使用>>运算符,因为这将永远留在输入“\ n”的。 这意味着你可以使用检索“\ n”字符(函数getline())的方法,也可以手动后记取出(忽略())。
文章来源: Is this a bug with getline(), or am I doing something wrong. Right way to use getline()?