如何阻止程序跳过 getline?
这是我的主程序,
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";
}
}
当输入关键字时,程序立即输出:
输入名字:输入姓氏:
完全绕过输入名字的能力。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在此之后,只需吃掉该行的末尾,
否则,您输入命令的行中的 '\n' 不会被消耗,下一个读取行只会读取它。华泰
after this just eat the end of the line
Otherwise the '\n' in the line where you input command is not consumed and the next readline reads just it. HTH
cin>>命令
不会从输入流中提取换行符('\n'
);当您调用 getline() 时它仍然存在。因此,您需要对getline()
(或ignore()
)进行额外的虚拟调用来处理此问题。cin >> command
does not extract the newline character ('\n'
) from the input stream; it's still there when you callgetline()
. Therefore, you need an extra dummy call togetline()
(orignore()
) to deal with this.正如其他人所提到的,问题在于,在读取命令时,您将行尾字符留在缓冲区中。除了 @Armen Tsirunyan 提出的替代方案之外,您还可以使用其他两种方法:
使用
std::istream::ignore
来实现:cin.ignore( 1024, '\n' );
(假设行的宽度不超过 1024 个字符。只需将
cin >> command
替换为getline( cin , command )
。只需 第一个较弱(在行很长的情况下),第二个替代方案修改了语义,因为现在整个第一行(不仅仅是第一个单词)被作为命令处理,但这可能没问题,因为它允许您执行更严格的输入检查(命令按照第一个单词的要求拼写,并且命令行中没有额外的选项。
如果您有不同的命令集,并且有些命令可能需要参数,您可以一次性读取命令行,然后从那里读取命令和参数:
As mentioned by others, the problem is that while reading the command you are leaving the end of line character in the buffer. Besides the alternative proposed by @Armen Tsirunyan, you can use two other approaches:
Use
std::istream::ignore
for that:cin.ignore( 1024, '\n' );
(assuming that lines will not be greater than 1024 characters in width.Just replace
cin >> command
withgetline( cin, command )
.Neither alternative requires creating an extra string, the first is weaker (in the event of very long lines), the second alternative modifies the semantics, as now the whole first line (not just the first word) is processed as the command, but this might be fine as it allows you to perform tighter input checking (the command is spelled as required in the first word, and there are no extra options in the command line.
If you have different set of commands and some might need an argument, you can read the command line in one pass, and then read the command and arguments from there: