naxchange
naxchange

Reputation: 913

c++: istringstream

I am creating a simple command parser using c++, and I am trying to use istream >> to check whether I am inputting a number or a character.

input:

a = 10
b = a

parser.cpp:

string inputLine, varLeft, equal, varRight;
double varValue
// please see update below
while(getline(cin, inputLine)){
    istringstream stringSplitter(inputLine);
    stringSplitter >> varLeft >> equal;

    if(!(stringSplitter >> varValue)){
        stringSplitter >> varRight;
    }
}    

The goal is, later in the code, if varRight is empty, I assume that the line of input was a double literal, otherwise, it's a string that denotes a variable. I understand there might be logical errors associated with mixed input starting with digits, but I am assuming that all input is correctly formatted for now. Why is the a in the second line of input discarded? What fix do you propose?

Update

The problem is not with the while loop statement, it is with the if statement at the end of the while code block.

In the actual code, the loop is not actually a while loop; I am using a vector object holding string commands, and iterating through them using a for loop which goes through the vector using iterators. But, in order to please the commenters, I have fixed it above.

Upvotes: 2

Views: 527

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110748

If an input function fails, the stream will not allow any more extractions until you clear the failure state. You'll need to do that, after you've checked that the input to varValue failed, with std::basic_ios::clear:

if(!(stringSplitter >> varValue)){
  stringSplitter.clear();
  stringSplitter >> varRight;
}

I don't know how you're doing /* not end of input */ at the moment (hopefully you're not checking eof()!), but it's recommended that you do:

while (getline(cin, inputLine)) {
  // ...
}

This checks that the line input was successful before diving into the loop.

Upvotes: 3

Related Questions