c - 在c中找到一组数字的范围

标签 c

#include "stdafx.h"

int main()
{
    int num, max = -32768, min = 32767, range;
    char choice = 'y';
    while (choice == 'y')
    {
        printf("\nenter any number ");
        scanf("%d", &num);
        if (num>max)
            max = num;
        if (num<min)
            min = num;
        range = max - min;
        printf("Range Is %d", range);
        printf("\nYou Want To Add Another Number(y/n) ");
        fflush(stdin);
        scanf("%c", &choice);
    }
    return 0;
}

一次输入后,即使按下“y”键,控制也会从程序中退出。 我想了解为什么它会退出我的主循环

最佳答案

您的代码的问题在于 scanf 保留了“\n”输入。

您应该开始使用 readline 而不是 scanf,参见 here了解更多信息

#include <stdlib.h>
#include <stdio.h>

int     main()
{
  int           ret, num, max = -32768, min = 32767, range;
  char          *line = NULL;
  size_t        len = 0;
  ssize_t       read;
  char          choice = 'y';

  ret = 0;
  while (choice == 'y')
    {
      printf("\nenter any number ");
      if ((read = getline(&line, &len, stdin)) == -1)
        break ;
      num = atoi(line);
      if (num > max)
        max = num;
      if (num < min)
        min = num;
      range = max - min;
      printf("Range Is %d", range);
      printf("\nYou Want To Add Another Number(y/n) ");
      if ((read = getline(&line, &len, stdin)) == -1)
        break ;
      choice = line[0];
    }
  if (line) // line should be freed even if getline failed
    free(line);
  return 0;
}

那么它是如何工作的?:

if ((read = getline(&line, &len, stdin)) == -1)
  break ; // break the while if getline failed

这里 getline 接受 3 参数:

  • 指向存储用户输入的的指针
  • 指向 len 的指针,其中 line 的大小以字节为单位存储
  • stdin 是标准输入的文件流(FILE *)

来自 man 3 getline

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.

If *lineptr is set to NULL and *n is set 0 before the call, then getline() will allocate a buffer for storing the line. This buffer should be freed by the user program even if getline() failed.

关于c - 在c中找到一组数字的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39589824/

相关文章:

C linux shmget 参数无效

c - 将数据写入二进制文件

c - 如何在不转到下一行的情况下在 C 中使用 printf() 和 scanf()?

c - 我如何制作一个函数来计算我的订单总数并将价格相加?

c - 使用 qsort 对二维数组进行排序时发出警告

c - 随机访问 union 数组的成员

c - 发生错误时,scanf 返回 1 而不是 0

c - 使用 fopen 和测试 NULL 的奇怪 C 行为

c - POSIX pthread 编程

C中的引用调用