user1701840 user1701840 - 1 month ago 7
C++ Question

what is the correct way to handle multiple input command differently in c++?

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.

Answer

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