自从我用C语言编写任何东西已经有一段时间了,所以我需要一些帮助。以下代码有某种错误。当我运行代码时,会跳过if
和else if
,并在屏幕上显示我的硬编码错误。
void play_tictactoe()
{
int row = 0, column = 0, i, win = 0;
char letter = 0;
char board[3][3] =
{
{' ',' ',' '},
{' ',' ',' '},
{' ',' ',' '}
};
printf( "\nDo you want to be X or O: " );
scanf( "%c", &letter );
if( letter == 'x' || letter == 'X' )
{
for( i = 0; i > 9 && win == 0; i++ )
{
printf( "\nPlace X: Row 1-3 and Column 1-3 (i.e. 1,3 for Row 1 and Column 3): " );
scanf( "%i,%i", &row, &column );
do
{
playersTurnX( &row, &column, board );
computersTurnX( &row, &column, board );
}
while( row > 3 || column > 3);
}
}
else if( letter == 'o' || letter == 'O' )
{
for( i = 0; i > 9 && win == 0; i++ )
{
printf( "\nPlace O: Row 1-3 and Column 1-3 (i.e. 1,3 for Row 1 and Column 3): " );
scanf( "%i,%i", &row, &column );
do
{
//computersTurnO( &row, &column, &board );
//playersTurnO( &row, &column, &board );
}
while( row > 3 || column > 3);
}
}
else
{
printf( "\nError!!!!\tInvalid entry.\n" );
}
}
答案 0 :(得分:2)
使用时:
hello
您最终会将换行符读入scanf( "%c", &letter );
。使用:
c
使用scanf( " %c", &letter );
// ^^^^ add a space before %c.
将确保跳过所有空格字符,并且只有非空白字符将被读入" %c"
。
答案 1 :(得分:2)
通常你想在%c之前添加一个空格来占用空格:
scanf( " %c", &letter );
有关详细信息,请参阅此处:https://gsamaras.wordpress.com/code/caution-when-reading-char-with-scanf-c/