我有一个程序可以接收用户的命令,它将以不同的方式处理不同的命令。
例如:
ADD_STUDENT ALEX 5.11 175
ADD_TEACHER MERY 5.4 120 70000
PRINT MERY
REMOVE ALEX
PRINT TEACHER SALARY
PRINTALL
因此,我需要检查每一行,看看输入内容是什么。
这是我的代码,但我认为我误解了iss <有人可以给我一个建议吗?并告诉我为什么我的代码无法按我预期的那样工作?
string line;
while(getline(cin, line))
{
//some initialization of string, float variable
std::istringstream iss(line);
if(iss >> command >> name >> height >> weight)
..examine the command is correct(ADD_STUDENT) and then do something..
else if(iss >> command >> name >> height >> weight >> salary)
..examine the command is correct(ADD_TEACHER) and then do something...
else if(iss >> command >> name)
..examine the command is correct(REMOVE) and then do somethin...
}
我的想法是,如果所有参数都已填写,则iss >>第一>> second >>第三将返回true
如果参数不足,则返回false。但是显然我错了。
最佳答案
这样做:
iss >> command;
if (!iss)
cout << "error: can not read command\n";
else if (command == "ADD_STUDENT")
iss >> name >> height >> weight;
else if (command == "ADD_TEACHER")
iss >> name >> height >> weight >> salary;
else if ...