如何阻止程序跳过getline? [英] How do I stop program from skipping over getline?
本文介绍了如何阻止程序跳过getline?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的主程序,
int main(){
string command;
cin>>命令;
if(command ==keyword)
{
string str,str2,str3,str4;
cout<< 输入名字:;
getline(cin,str);
cout<< 输入姓氏:;
getline(cin,str2);
cout<< 输入年龄:;
getline(cin,str3);
cout<<输入国家:;
getline(cin,str4);
cout<< 谢谢,<< str <<<< str3<<< str3<< .\\\
;
}
}
输入关键字时,程序立即输出: / p>
输入名字:输入姓氏:
完全绕过输入名字的能力。
解决方案
string command;
cin>>命令;
之后就吃完了
string restOfLine;
getline(cin,restOfLine);
否则,不输入命令的行中的'\\\
'只读它。 HTH
This is my main program,
int main () {
string command;
cin>>command;
if(command == "keyword")
{
string str, str2, str3, str4;
cout << "Enter first name: ";
getline (cin,str);
cout << "Enter last name: ";
getline (cin,str2);
cout << "Enter age: ";
getline (cin,str3);
cout<<"Enter country: ";
getline (cin,str4);
cout << "Thank you, " << str <<" "<<str2 <<" "<<str3<<" "<<str4<< ".\n";
}
}
When keyword is entered, the program immediately outputs :
Enter first name: Enter last name:
completely bypassing the ability to enter the first name.
解决方案
string command;
cin>>command;
after this just eat the end of the line
string restOfLine;
getline(cin, restOfLine);
Otherwise the '\n' in the line where you input command is not consumed and the next readline reads just it. HTH
这篇关于如何阻止程序跳过getline?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文