我对此有很大的麻烦...
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
;
}
希望这可以帮助!
编辑:为了回答更详细的问题,这里有一个更合适的答案。:-)
这段代码的问题是当你写
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 for一秒钟,它将读取整个缓冲区,直到换行符为止。
printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);
> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234