使用fgets和strtol获取单个整数

我正在学习C,我正在尝试使用fgets()strtol()来接受用户输入,只需要取第一个字符。 我将创建一个菜单,允许用户选择选项1-3和4退出。 如果选择“1”,“2”,“3”或“4”,我希望仅选择每个选项。 我不希望’asdfasdf’工作。 我也不希望’11212’选择第一个选项,因为它从1开始。到目前为止我创建了这个代码,当我开始测试时,由于某种原因,这循环了问题并为输入提供了0。

#include  #include  int main() { char a[2]; long b; while(1) { printf("Enter a number: "); fgets(a, 2, stdin); b = strtol(a, NULL, 10); printf("b: %d\n", b); } return 0; } 

产量

 Enter a number: 3 b: 3 Enter a number: b: 0 Enter a number: 

它应该是:

 Enter a number: 3 b: 3 Enter a number: 9 b: 9 

您需要有足够的空间来读取'\n' ,否则它将被保留在输入缓冲区中,下一次迭代将立即读取,从而使fgets()返回一个空字符串,因此strtol()返回0

读取fgets()的文档,直到'\n'或直到缓冲区已满为止。 所以第一次,它停止,因为它没有更多的空间来存储字符,然后第二次仍然必须读取'\n'并立即停止。

一种可能的解决方案是增加缓冲区大小,以便读取'\n'并将其存储在其中。

另一种解决方案是在fgets()之后读取所有剩余的字符。

第二个解决方案可以通过一次读取一个字符来干净地实现,因为您只对第一个字符感兴趣,您可以丢弃其他任何字符

 #include  #include  int main() { int chr; while (1) { // Read the next character in the input buffer chr = fgetc(stdin); // Check if the value is in range if ((chr >= '0') && (chr <= '9')) { int value; // Compute the corresponding integer value = chr - '0'; fprintf(stdout, "value: %d\n", value); } else { fprintf(stderr, "unexpected character: %c\n", chr); } // Remove remaining characters from the // input buffer. while (((chr = fgetc(stdin)) != '\n') && (chr != EOF)) ; } return 0; }