这个小测试有助于查明我的程序中的问题。现在发生了一件奇怪的事情:第三条也是最后scanf()
一条被跳过了,紧随其后的测试行将打印出10的值cBoard[*tile]
。
void takeTurn(int *iap, int *tile, char *cap) {
printf("\n\tPRINT TEST Take Turn()\n");
if (*iap == 1) *cap == 'X';
if (*iap == 2) *cap == 'O';
printf("\nWhich tile would you like?");
printf("\n\tTEST the value of cBoard[0] is %c. At [3] is %c.\n1 ::", cBoard[0], cBoard[3]);
scanf("%c", &cBoard[0]);
//user inputs 'h'.
printf("\n\tTEST the value of cBoard[0] is now %c\n2 ::", cBoard[0]);
scanf("%d", tile);
//it prints
//TEST the value of cBoard[0] is now h
//user inputs 6. It prints
printf("\n\tTEST the value of cBoard[%d] is %d.\n3 ::", *tile, cBoard[*tile]+1);
//it prints
//TEST the value of cBoard[6] is 1.
scanf("%c", &cBoard[*tile]);
//This scanf() does not run.
printf("\n\tTEST the value of cBoard[%d] is %d.\n", *tile, cBoard[*tile]);
//it prints
//TEST the value of cBoard[6] is 10.
...
}
cBoard[6]
不管先前的分配是什么,最终的打印结果都会返回10。关于功能不正常的某些原因scanf()
必须将新值设置为10。
到底是怎么回事?
scanf("%d", tile);
读取一个数字,但将其保留'\n'
在标准输入缓冲区中。下一个读取操作scanf("%c", &cBoard[*tile]);
将读取此字符,该字符恰好具有10
ASCII值。您可以通过忽略字符前面的空格来解决此问题:
scanf(" %c", &cBoard[*tile]); // notice the space before the %c
还要注意,您应该检查返回值scanf
以验证是否提供了正确的输入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句