c - 获取用户输入并在需要时停止循环 C

标签 c user-input

我需要从用户那里获取给定范围内的输入整数。我需要得到他们的低点和高点。但循环并没有停止,我不知道为什么。我以为我的条件很好,但循环不会停止。

int     obtainNumberBetween (const char* descriptionCPtr, int low, int high) {
  char  line[MAX_LINE];
  int   entry;
//  #define     MAX_LINE    256

  // YOUR CODE HERE
 do
  {
    printf("Please enter the lowest number in the range (%d-%d):\n " ,RANGE_LOWEST ,RANGE_HIGHEST);
    fgets(line, 256, stdin);
    low = atoi(line);
    printf ("The value entered is %d\n", low);

  }
  while  ( (entry < low) || (entry > high) );

return(entry);

}

应有的示例输出:

Please enter the lowest number in the range (0-32767): -6
Please enter the lowest number in the range (0-32767): 1
Please enter the highest number in the range (1-32767): 0
Please enter the highest number in the range (1-32767): 32768
Please enter the highest number in the range (1-32767): 512

最佳答案

您的entry变量未初始化。所以这一行调用了一个未定义的行为:

while  ( (entry < low) || (entry > high) )

也许您应该将用户输入分配给条目,而不是low

关于c - 获取用户输入并在需要时停止循环 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41800077/

相关文章:

c - 打印指针的值时是否需要间接运算符?

php - 在 php 中处理用户输入数据。什么更好?

linux - 在 Linux 中运行 R 脚本时等待用户输入

c - 没有 math.h 的对数计算

c - 我可以通过哪些方式(使用 stdio)打印垂直直方图

c - 为什么清除中断标志会导致 C 中的段错误?

java - 直接在ArrayList中获取输入

bash - 如何在(负)Bash 条件下使用 OR

loops - Haskell - 我如何摆脱互动?

php - 相同的算法在 C 和 PHP 中运行不同