C++ if condition not checked after goto

一笑奈何 提交于 2019-12-02 13:39:36

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.";
    }

}

For debugging purpose at least, why not do

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!