Help with my tictactoe project

Hey!

I'm currently working on a tictactoe project, but I'm having some issues.
I have 2 different players and before the game I ask for their names in the program

1
2
3
4
5
6
7
8
#include <iostream>
#include <string>
using namespace std;

cout << "Player 1 what is your name? ";
cin >> player1;
cout << "Player 2 what is your name? ";
cin >> player2;


but if player1 types for exc "John Wood" the player1 input will take the John in and player2 input will accept the Wood and I'm about to lose my mind over this one. I tried using getline(cin, player1), but for some reason couldn't get any input option from that. Is there any way for me to consider the entire name (John Wood) as one string or just take ignore the second part and take the John as input?

I have pretty much the same issue abit later when im asking for input for the game itself

I have matrix for the tictactoe that looks like this:

1 2 3
4 5 6
7 8 9

lets say if player X types in "2 3" the game will place X -> 2 and O -> 3 and its X's turn again (skips O). This input is currently defined as an integer
Hello div132,

This should help understand how "cin" works:
http://www.cplusplus.com/doc/tutorial/basic_io/

In the case of getting a full name you will want to use std::getline(std::cin, player1);. This will retrieve the entire name.

Hope that helps,

Andy

P.S. Post the whole code so I and everyone else can see what you did.
Last edited on
To summarize briefly the link that Handy Andy posted, a cin >> operation reads up until white space, so if the user enters "John Wood", a single cin operation retrieves only "John" from the input buffer, leaving "Wood" in the input buffer.

As Handy Andy said you should use std::getline(). getline() reads until a specified delimiter, by default \n, thereby returning all of "John Wood". You indicate that you tried getline(), but don't really indicate why you think that didn't work.

BTW, in the code snippet you posted, player1 and player2 are not defined. It's not clear if you have declared player1 and player2 as std::string.

I have pretty much the same issue a bit later when I'm asking for input for the game itself

When switching between cin >> and getline(), it's a good idea to do:
1
2
  cin.clear();               // reset any error flags on the stream
  cin.ignore (1000);    // eat any extraneous characters in the input buffer 






Thanks alot for the tips! getline started working after i added cin.ignore() and cin.clear(). And the code itself is way too long to be entirely posted but both players were defined as std::string
Topic archived. No new replies allowed.