-
1 Attachment(s)
Looping and inputing
I have just started to learn C++, and am trying to make a O's & X's program to test what I have learned from the tutorials here.
My problem is that after the first input line, every other input line is outputed twice, here's the problem code:
Code:
void game()
{
char place[2], piece='O';
int x=0, y=0;
draw_board();
while(!win())
{
cout << endl << piece << " enter a position>"; // this is the line outputed twice
cin.getline(place,3,'\n');
switch(place[0])
{case 't': x=0; break;
case 'm': x=1; break;
case 'b': x=2; break;
default : x=3;
}
switch(place[1])
{case 'l': y=0; break;
case 'm': y=1; break;
case 'r': y=2; break;
default : y=3;
}
if(x!=3 && y!=3)
{
board[x][y]=piece;
chg_plr(&piece);
draw_board();
}
};
}
can anyone offer an idea why the line is printed twice?:confused:
if you wish to see the rest, it is included as an attachment (I know that win isn't properly coded yet, I just used that temporarily)
-
The program crashed with me because you have there char place[2] but the user usually enters two characters and '\0' is added to the end. char place[3] fixes that problem.
-
Thanks for that, I wonder why Visual C++ didn't spot that
-
Actually it's because cin.getline(place,3,'\n'); can't know how big the passed buffer is. In C++ you can also use std::strings:
// #include <string>
std::string place;
std::getline(std::cin,place);
-
what's a std::string, I've never seen that before