如何从C语言中的stdio获取整数?

问题描述 投票:26回答:3

我对此有很大的麻烦...

printf("> ");
int x = getchar();

printf("got the number: %d", scanf("%d", &x));

输出

> 1234
got the number: 1
c stdio
3个回答
52
投票

我不确定您要查找的是什么,但是如果您的问题是如何使用<stdio.h>读取整数,则正确的语法是

int myInt;
scanf("%d", &myInt);

当然,您需要进行很多错误处理以确保其正确运行,但这应该是一个好的开始。特别是,您需要处理以下情况:

  1. stdin文件已关闭或损坏,所以您什么都没有得到。
  2. 用户输入的内容无效。

要进行检查,您可以像这样从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);

希望这会有所帮助!


6
投票

典型的方法是使用scanf

int input_value;

scanf("%d", &input_value);

但是,在大多数情况下,您要检查读取输入的尝试是否成功。 scanf返回成功转换的项目数,因此您通常希望将返回值与预期读取的项目数进行比较。在这种情况下,您希望阅读一项,所以:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

当然,所有scanf系列(sscanffscanf等)都是一样。


2
投票

解决方案非常简单...您正在读取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
© www.soinside.com 2019 - 2024. All rights reserved.