I was wondering, what is the easiest way to ignore the rest of an input line if there is bad input from the first word in a string. Essentially I read a command in from cin, and if it's a bad command I want to skip the rest of the line. For example:
insrt something
so it reads in insrt as a command, realizes it's a bad command, prints an error message, and then I want it to skip the rest of the line (the "something" essentially)
The problem I'm having is if the bad command is something like:
yikes that's bad
It prints the proper error message, and if I enter another command, it will work. But if the command is something like:
yikes
Then the next command I enter is not read in
This is what I was trying within a while loop that reads while(cin >> command):
It doesn't. It works if I have an invalid command with parameters, but if it is just an invalid command without parameters, the following command doesn't seem to be read in to the command variable
If the line ends directly after the command then cin.ignore(); on line 2 will discard the newline character. getline just search for the next newline character it can find but because you have already removed the newline character it will read the line that follows (and wait if it has not been entered yet).
I solved this by putting the cin.ignore() on line 2 within this:
1 2 3
if(isspace(cin.peek())){
cin.ignore();
}
I'm still getting the same problem though. The issue I seem to be running into is that if it's a newline, cin.peek() checks the next line, which for both cases will return isspace(cin.peek()) to return false
I essentially think I need to revise this to something like:
1 2 3 4 5 6 7
if(there was a newline character){
//do nothing
{
elseif(!isspace(cin.peek())){
getline(cin, command);
}
I'm not entirely sure how to check for this though...
Alright so I figured out a way to do it, if you know of a better way though feel free to let me know. Essentially I made a bool variable called oneCommand that is set to true if there is a '\n' char returned from cin.peek() like so:
Since your input is in a series of lines and each line stands alone, I would be inclined to use a combination of getline and stringstream:
1 2 3 4 5 6 7 8 9
string line;
while (getline(cin, line))
{ // Have a full line
stringstrem ss (line); // create a stream from the line just read
ss >> command;
// Parse additional tokens from ss as required
// If at some point I don't like the command, I can just continue with the next iteration of the loop.
// cin is alreay pointing to the next line.
}