需要帮助getline() [英] Need help with getline()
问题描述
是否有理由为什么如果在我的程序中我要求用户输入,我这样做:
int number ;
string str
int accountNumber;
cout<< 输入数字:;
cin>>数;
cout<< 输入名字:;
getline(cin,str);
cout<< 输入帐号:;
cin>>帐号;
为什么在输入第一个数字后,输出Enter Name,然后输入Enter Account Number 之前,我甚至得到输入我的str的getline(cin,str)行?谢谢!
getline(cin,str);
在之前读取的数字之后的换行符,并立即返回此行。为避免出现这种情况,您可以在读取名称之前用 std :: ws
跳过空格:
cout<< 输入数字:;
str 不会以空格开头,即使用户输入了。但在这种情况下,这可能是一个功能,而不是一个bug ...
cin>>数;
cout<< 输入名字:;
ws(cin);
getline(cin,str);请注意,这还会跳过换行符后面的前导空格,因此<$ <$> $ <$> <$>
Is there a reason why if in my program I am asking the user for input, and I do:
int number; string str; int accountNumber; cout << "Enter number:"; cin >> number; cout << "Enter name:"; getline(cin, str); cout << "Enter account number:"; cin >> accountNumber;
Why after inputting the first number, it outputs "Enter Name", followed immediately by "Enter Account Number" before I even get to input my "str" for the getline(cin, str) line? Thanks!
解决方案The
getline(cin, str);
reads the newline that comes after the number read previously, and immediately returns with this "line". To avoid this you can skip whitespace withstd::ws
before reading the name:cout << "Enter number:"; cin >> number; cout << "Enter name:"; ws(cin); getline(cin, str); ...
Note that this also skips leading whitespace after the newline, so
str
will not start with spaces, even if the user did input them. But in this case that's probably a feature, not a bug...这篇关于需要帮助getline()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!