Hello, I am programming a relatively advanced Tic-Tac-Toe game, and I am having trouble with using the getline() command in the <string> library.
It is not a big deal that this is fixed, as the game can function without it, but I thought it would be nice if the player could enter both his first and last name. There is no error that occurs, but when compiled it simply skips over the user input and jumps straight to the return.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string OnePlayerGame()
{
NumberOfPlayers = 1;
cout << "You have selected a one player game, your opponent will be the computer.\n\nEnter Your Player Name: ";
std::getline(cin, PlayerOneName);
return PlayerOneName;
}
string TwoPlayerGame()
{
NumberOfPlayers = 2;
cout << "You have selected a two player game, your opponent will be another human.\n\nEnter Player One Name: ";
std::getline(cin, PlayerOneName);
cout << "\nEnter Player Two Name: ";
std::getline(cin, PlayerTwoName);
return (PlayerOneName, PlayerTwoName);
}
These are the two string classes for the two different game types. If you need the rest of the code, just ask.
At any point before you call OnePlayerGame() or TwoPlayerGame(), do you have something like cin >> FOO? That instruction will leave a newline character in the buffer, which the getline calls will catch. That will make it appear as if it were skipped over.
Random Note:
Line 15 will only return PlayerTwoName. You cannot return multiple values like that.
@Daleth: Yes I do, and it is essential to the code. Is there any way to work around this, so that the newline character is removed from the buffer?
@Paoletti301: I tried this, and it did not work.
@Paoletti: getline() by default uses a delim of '\n' so specifying like you suggesting wouldn't affect the result. The issue was as result of what Daleth said about cin>> leaving trailing whitespace like newlines in the buffer.