C++ 如何阻止程序跳过getline?
这是我的主要节目C++ 如何阻止程序跳过getline?,c++,input,getline,C++,Input,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 n
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";
}
}
int main(){
字符串命令;
cin>>命令;
如果(命令==“关键字”)
{
字符串str、str2、str3、str4;
库特
在这之后,只吃线的末端
string restOfLine;
getline(cin, restOfLine);
否则,您输入命令的行中的“\n”不会被使用,而下一个读取行只读取它。HTHcin>>command
不会从输入流中提取换行符('\n'
);当您调用getline()
时,它仍然存在。因此,您需要对getline()进行额外的伪调用
(或ignore()
)来处理此问题。如其他人所述,问题是在读取命令时,您将行尾字符保留在缓冲区中。除了@Armen Tsirunyan提出的替代方法外,您还可以使用两种其他方法:
- 使用
std::istream::ignore
表示:cin.ignore(1024,\n');
(假设行的宽度不超过1024个字符)
- 只需将
cin>>命令
替换为getline(cin,command)
这两个备选方案都不需要创建额外的字符串,第一个更弱(在非常长的行的情况下),第二个备选方案修改语义,因为现在整个第一行(不仅仅是第一个单词)都作为命令处理,但这可能很好,因为它允许您执行更严格的输入检查(命令按照第一个单词中的要求拼写,并且命令行中没有额外的选项
如果您有不同的命令集,有些命令可能需要参数,则可以一次读取命令行,然后从中读取命令和参数:
std::string commandline;
std::vector<std::string> parsed_command;
getline( cin, commandline );
std::istringstream cmdin( commandline );
std::copy( std::istream_iterator<std::string>(cmdin), std::istream_iterator(),
std::back_inserter( parsed_command ) );
// Here parsed_command is a vector of word tokens from the first line:
// parsed_command[0] is the command, parsed_command[1] ... are the arguments
std::string命令行;
std::向量解析_命令;
getline(cin,命令行);
std::istringstream cmdin(命令行);
std::copy(std::istream\u迭代器(cmdin),std::istream\u迭代器(),
std::back_插入器(解析的_命令));
//这里,parsed_命令是来自第一行的单词标记向量:
//parsed_命令[0]是命令,parsed_命令[1]…是参数
Special可以让这更简单。
std::string commandline;
std::vector<std::string> parsed_command;
getline( cin, commandline );
std::istringstream cmdin( commandline );
std::copy( std::istream_iterator<std::string>(cmdin), std::istream_iterator(),
std::back_inserter( parsed_command ) );
// Here parsed_command is a vector of word tokens from the first line:
// parsed_command[0] is the command, parsed_command[1] ... are the arguments