C++ if condition not checked after goto

2019-03-07 05:30发布

问题:

I'm working on a simplish game (this isn't the whole code, just the bit that I'm having issues with) and I've run into this issue; After the condition is furfilled, it goes back to the start and it offers me to reenter the string, however, whatever I enter, I just get 'Not Valid'. Does anyone know why? I'm using the GNU C++ Compiler.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string command;
mainscreen:
    cout << "blab";
getlinething:
    cin.ignore();
    getline(cin, command);
    if (command == "task")
    {
        goto mainscreen;
    }
    else
    {
        cout << "Not valid.";
        goto getlinething;
    }
    return 0;
}

回答1:

When I run your code with a debug print it shows that each time you read a new command you are loosing the first char of the string. In fact, when I remove your cin.ignore() it works fine. Also, have a look at this while to see if it fits your needs:

cout << "blab";
while(1){
    getline(cin, command);
    if(command == "task"){
        cout << "blab";
        getline(cin, command);
    }
    else{
        cout << "Not valid.";
    }

}


回答2:

For debugging purpose at least, why not do

cout << "'" << command << "' Not valid" << endl ;


回答3:

Alright, I tested it out. Without cin.ignore(), I cannot enter the data into the string at all. The first time I enter it captures everything. So if I wrote task, the string would say 'task', however the second time I entered it, it would say 'ask'. I don't really know why it's doing that.



回答4:

The cin.ignore() line will always discard one character by default (unless it encounters EOF, which would be a fairly deliberate act on cin).

So, let's say the user enters task and then hits the enter key. The cin.ignore() will discard the 't', and the command string will contain "ask". If you want to get a match, the first time through, the user will need to enter ttask. The newline will be discarded, in either case. The same will happen until a match is encountered.