#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, thengetline()
will allocate a buffer for storing the line. This buffer should be freed by the user program even ifgetline()
failed.
关于c - 在c中找到一组数字的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39589824/