2010-11-01 61 views
2

这是我的主要程序,如何阻止程序跳过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"; 
    } 
} 

当输入关键字时,该程序立即输出:

输入名字:输入名字:

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

回答

3
string command; 
cin>>command; 

在此之后只是吃行

string restOfLine; 
getline(cin, restOfLine); 

结束,否则在你输入的命令不消耗线路和一个readline的“\ n”只是读取它。 HTH

+1

特别[ignoreline和“blankline提取器“函数](http://bitbucket.org/kniht/scraps/src/fdf116645350/cpp/kniht/clinput.hpp#cl-28)可以使这更容易。 – 2010-11-01 08:06:16

+0

namespace'kniht'? – 2010-11-01 08:09:46

3

cin >> command不会从输入流中提取换行符('\n')当您拨打getline()时仍然存在。因此,您需要额外拨打getline()(或ignore())来处理此问题。

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