我刚刚遇到了这段代码,它允许用户在命令提示符中输入字符串。我知道他们所做的一切,这一切都很棒。但我有一个关于 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 ;
现在,当这是输出时,我得到如下内容:(使用 john smith 作为输入)
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 ;
当你再次输入你的全名后,我突然收到换行符。老实说,这并不是一个大问题。但如果有人能帮助我,我不介意知道发生了什么。谢谢!