Question

I am writing a program which gets the user's string input and parses it by white spaces.

Since the program needs to repeatedly receive user input until the user enters "exit", I put all my codes in a while loop as below:

while(cont == true)
{
    cin>>command;
    string parsedStr[3];
    parsedStr[0] = "";
    parsedStr[1] = "";
    parsedStr[2] = "";
    int j = 0;

    for(i=0; i<command.size(); i++)
    {   
        if (command[i] == ' ')
        {
            ++j;                
        }
        parsedStr[j] += command[i];
    }

    cout<<"Command: "<<parsedStr[0]<<"\n";
    cout<<"Argument 1: "<<parsedStr[1]<<"\n";
    cout<<"Argument 2: "<<parsedStr[2]<<"\n";

    /* do my desired operations according to the received command */
}

This is however when I enter a command such as "execute 12 345", it will show the below result and doesn't parse the argument:

Command: execute
Argument 1:
Argument 2:
Command: 12
Argument 1:
Argument 2:
Command: 345
Argument 1:
Argument 2:

But when I move the parser out of the while loop, it works perfectly and prints out the followings:

Command: execute
Argument 1: 12
Argument 2: 345

What should I do?

Was it helpful?

Solution

This is because you are reading a string using

cin >> command;

The >> operator stops at the space, so your command ends up with no spaces in it. The next iteration of the loop picks up the first argument and tries to parse it; then the next iteration does the same with the last argument.

You can make your code work by using std::getline instead:

getline(cin, command);

But an easier way to do the same thing is to use >> operator correctly:

cin >> parsedStr[0];
cin >> parsedStr[1];
cin >> parsedStr[2];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top