2

这是我的主要程序,

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";
    }
}

输入关键字后,程序立即输出:

输入名字: 输入姓氏:

完全绕过输入名字的能力。

4

3 回答 3

3
string command;
cin>>command;

在这之后就吃线的末端

string restOfLine;
getline(cin, restOfLine);

否则,您输入命令的行中的 '\n' 不会被消耗,并且下一个 readline 只会读取它。高温高压

于 2010-11-01T07:35:04.673 回答
3

cin >> command'\n'不从输入流中提取换行符 ( );当你打电话时它仍然存在getline()getline()因此,您需要对(或) 进行额外的虚拟调用ignore()来处理此问题。

于 2010-11-01T07:38:24.063 回答
1

正如其他人所提到的,问题是在读取命令时,您将行尾字符留在缓冲区中。除了@Armen Tsirunyan 提出的替代方案,您还可以使用其他两种方法:

  • 用于std::istream::ignore:(cin.ignore( 1024, '\n' );假设行的宽度不会超过 1024 个字符。

  • 只需替换cin >> commandgetline( 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
于 2010-11-01T08:53:23.327 回答