我刚看到这段代码,它允许用户在命令提示符中输入字符串。我知道它们的功能并且都很好。但是,我对cin和getline()函数有一个问题。
string name ;
cout << "Please enter your full name: " ;
cin >> name ;
cout << "Welcome " << name << endl ;
cout << "Please enter your full name again please: " ;
getline(cin , name) ;
cout << "That's better, thanks " << name << endl ;
return 0 ;
现在输出这个时,我得到了类似以下内容的结果:(以输入的约翰·史密斯为例)
Please enter your full name: john smith
Welcome John
Please enter your full name again: That's better thanks Smith
我理解为什么会出现这种情况,因为getline仍在读取输入缓冲区,我知道如何解决。我的问题是,为什么在“请再次输入您的全名:”之后没有换行符?当我修改代码为:
string name ;
cout << "Please enter your full name: " ;
cin >> name ;
cout << "Welcome " << name << endl ;
cout << "Please enter your full name again please: " ;
cin.ignore( 256, '\n') ;
getline(cin , name) ;
cout << "That's better, thanks " << name << endl ;
return 0 ;
在重新输入您的全名后,突然出现了一个新行。说实话,这并不是什么大问题。但如果有人能帮我解决并告诉我发生了什么事情,我会很感激。谢谢!
std::numeric_limits<std::streamsize>::max()
。 - Konrad Rudolph#include <limits>
- Nemanja Boric