什么是正确的方式来处理多个输入命令在c ++中不同? [英] what is the correct way to handle multiple input command differently in c++?

查看:125
本文介绍了什么是正确的方式来处理多个输入命令在c ++中不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,从用户的命令,它将处理不同的命令不同。
例如:

  ADD_STUDENT ALEX 5.11 175 
ADD_TEACHER MERY 5.4 120 70000

REMOVE ALEX
打印教师薪金
PRINTALL

需要检查每一行,看看输入是什么。



这里是我的代码,但我认为我误解了iss<工作。
有人可以给我建议吗?告诉我为什么我的代码没有按我的预期工作。

  string行; 
while(getline(cin,line))
{
//字符串的一些初始化,float变量
std :: istringstream iss(line);
if(iss>> command>> name>> height>> weight)
..检查命令是否正确(ADD_STUDENT) $ b else if(iss>> command>> name>> height>> weight>> salary)
..检查命令是否正确(ADD_TEACHER) ...
else if(iss>> command>> name)
..检查命令是否正确(REMOVE),然后做某事...
}

我的想法是iss >> first >> second >> third将返回true如果所有的参数
,如果参数不足则返回false。但显然我错了。



<$>

p $ p> iss>>命令;
if(!iss)
cout<< error:can not read command\\\
;
else if(command ==ADD_STUDENT)
iss>> name>> height>>重量;
else if(command ==ADD_TEACHER)
iss>> name>> height>>重量>>薪水;
else if ...


I have a program that take commands from user and it will process different commands differently. For example:

ADD_STUDENT ALEX 5.11 175
ADD_TEACHER MERY 5.4  120 70000
PRINT MERY 
REMOVE ALEX
PRINT TEACHER SALARY
PRINTALL 

therefore, I need to examine each line and see what is the input consists of.

Here is my code, but I think I misunderstand the way iss<< work. Can someone give me a suggestion? And tell me how why my code didn't work as I expected?

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...
}

My thought is that the iss>> first >>second >> third will return true if all arguments are filled and false if not enough arguments. But apparently I am wrong.

解决方案

Do it like so:

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 ...

这篇关于什么是正确的方式来处理多个输入命令在c ++中不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆