[英]Why does this pointer becomes a default value of 10 after scanf()?
This small test has helped in pinpointing issues with my program. 这个小测试有助于查明我的程序中的问题。 Now a weird thing is happening: The third and final
scanf()
is getting skipped over and the test line immediately following prints a value of 10 for cBoard[*tile]
. 现在发生了一件奇怪的事情:第三个也是最后一个
scanf()
被跳过,紧随其后的测试行将cBoard[*tile]
的值打印为10。
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.
...
}
The final print returns cBoard[6]
as 10 regardless of whatever its previous assignment was. 最终打印结果将
cBoard[6]
返回10,而不管其先前分配的内容如何。 Something about the improperly functioning scanf()
must be setting the new value to 10. 关于
scanf()
不正常的某些原因,必须将新值设置为10。
What is going on? 到底是怎么回事?
scanf("%d", tile);
reads a number but leaves the '\\n'
in the standard input buffer. 读取数字,但在标准输入缓冲区中保留
'\\n'
。 The next read operation scanf("%c", &cBoard[*tile]);
下一个读取操作
scanf("%c", &cBoard[*tile]);
reads this character, which happens to have the value 10
in ASCII. 读取此字符,恰巧它的ASCII值为
10
。 You can fix the behavior by ignoring white space before the character with: 您可以通过忽略字符前面的空白来解决此问题:
scanf(" %c", &cBoard[*tile]); // notice the space before the %c
Note also that you should check the return value of scanf
to verify that correct input was provided. 还要注意,您应该检查
scanf
的返回值以验证是否提供了正确的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.