如何从C中的stdio获取int?

这有很大的麻烦……

printf("> "); int x = getchar(); printf("got the number: %d", scanf("%d", &x)); 

产量

 > 1234 got the number: 1 

我不完全确定这是你正在寻找的,但如果你的问题是如何使用读取整数,那么正确的语法是

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

当然,您需要进行大量的error handling以确保其正常工作,但这应该是一个良好的开端。 特别是,您需要处理其中的案例

  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 ; } 

希望这可以帮助!

编辑 :回答更详细的问题,这是一个更恰当的答案。 🙂

这段代码的问题在于你写的时候

 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); 

解决方案非常简单…你正在读取getchar(),它给你输入缓冲区中的第一个字符,而scanf只是将它解析(实际上不知道为什么)为一个整数,如果你忘记了getchar for第二,它会读取完整的缓冲区,直到换行符为char。

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

输出

 > [prompt expecting input, lets write:] 1234 [Enter] got the number: 1234