C Scanf 突然停止读取值

标签 c integer printf scanf

我正在尝试在我的 Mac 上运行一个简单的 C 程序。它工作了一段时间但突然 scanf 停止工作。我基本上想读入一个整数值并输出输入的内容。无论我输入的整数是多少,程序一直输出 0。我已经尝试了建议 here但没有任何效果。我试过在终端和 xcode 中运行该程序,但仍然没有。有什么想法吗?

#include <stdio.h>

int main(){
  int numberOfElements = 0;
  scanf("Number of elements: %d",&numberOfElements);
  printf("%d\n",numberOfElements); //keeps returning 0 no matter the number I enter
  return 0;
}

最佳答案

你必须打印提示,并且只扫描输入:

printf("Number of elements: ");
fflush(stdout);
scanf("%d", &numberOfElements);

一般来说,最好避免直接使用scanf()。相反,您可以获得一行输入,然后对检索到的字符串使用 sscanf() 以更好地控制错误。

char line[MAX_LINE];
if (fgets(line, sizeof(line), stdin) != NULL) {
    if (sscanf(line, "%d", &numberOfElements) != 1) {
        printf("You didn't input a number: %s", line);
        /* ... */
    }
}

关于C Scanf 突然停止读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16994747/

相关文章:

c++ - GCC下的_rotl64相当于什么

java - 如何将 int 转换为 String 并仍然计数?

Java 24 位数字签名

c - 为什么流的 C 函数以字符 f 开头?

C 程序不会打印行,已尝试刷新

c - 无法从 Linux 中的设备驱动程序调用 Fork()

c - fgets() 是否总是以 null 终止它返回的字符串?

Java 多维 ArrayList Int

c - 使用 getchar 输入字符串

c - GTK 中的启动画面