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;
}
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.
For debugging purpose at least, why not do
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:
The
cin.ignore()
line will always discard one character by default (unless it encountersEOF
, which would be a fairly deliberate act oncin
).So, let's say the user enters
task
and then hits the enter key. Thecin.ignore()
will discard the't'
, and thecommand
string will contain"ask"
. If you want to get a match, the first time through, the user will need to enterttask
. The newline will be discarded, in either case. The same will happen until a match is encountered.