我对此有很大的麻烦...
printf("> ");
int x = getchar();
printf("got the number: %d", scanf("%d", &x));
> 1234
got the number: 1
我不确定您要查找的是什么,但是如果您的问题是如何使用<stdio.h>
读取整数,则正确的语法是
int myInt;
scanf("%d", &myInt);
当然,您需要进行很多错误处理以确保其正确运行,但这应该是一个好的开始。特别是,您需要处理以下情况:
stdin
文件已关闭或损坏,所以您什么都没有得到。要进行检查,您可以像这样从scanf
捕获返回码:
int result = scanf("%d", &myInt);
如果stdin
在读取时遇到错误,则result
将为EOF
,您可以检查这样的错误:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
另一方面,如果用户输入了无效的内容,例如垃圾文本字符串,那么您需要从stdin
中读取字符,直到消耗掉所有有问题的输入为止。您可以按照以下步骤执行此操作,即如果未读取任何内容,则scanf
返回0:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
if (result == 0) {
while (fgetc(stdin) != '\n') // Read until a newline is found
;
}
希望这会有所帮助!
EDIT:针对更详细的问题,这是一个更合适的答案。 :-)
此代码的问题是在编写时
printf("got the number: %d", scanf("%d", &x));
这是从scanf
打印返回码,如果出现流错误,则返回EOF
;如果未读取任何内容,则返回0
;否则返回1
。特别是,这意味着,如果输入整数,将始终打印1
,因为您正在打印的是scanf
的状态码,而不是所读取的数字。
要解决此问题,请将其更改为
int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);
希望这会有所帮助!
典型的方法是使用scanf
:
int input_value;
scanf("%d", &input_value);
但是,在大多数情况下,您要检查读取输入的尝试是否成功。 scanf
返回成功转换的项目数,因此您通常希望将返回值与预期读取的项目数进行比较。在这种情况下,您希望阅读一项,所以:
if (scanf("%d", &input_value) == 1)
// it succeeded
else
// it failed
当然,所有scanf
系列(sscanf
,fscanf
等)都是一样。
解决方案非常简单...您正在读取getchar(),它为您提供了输入缓冲区中的第一个字符,而scanf只是将其解析为一个整数(真的不知道为什么),如果您只是忘记了getchar一秒钟,它将读取整个缓冲区,直到换行符为止。
printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);
> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234