int n;
int a[maxsize];
int b[maxsize];
int c[maxsize];
int i;
printf("enter number of elements(disks)\n");
scanf("%d",&n);
printf("enter the elements in ascending order\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
这种方法有时很好用,但大多数时候这段代码都会进入无限循环,“扫描”和“在循环中无限接受值,我尝试使用函数(fflush)来清除缓冲区内容,但仍然无法正常工作,有人请帮助我!请解释原因!!
答案 0 :(得分:1)
发布的代码无法进入无限循环,scanf()
函数可能会阻塞,直到您输入类似 Ctrl + D 的内容来结束输入流或者可能是另一个整数,问题是你是以一种非常危险的方式处理输入,因为你根本没有检查错误,你可能会想要做什么呢
#include <stdio.h>
#include <stdlib.h>
#define clearstdin() do {int chr; while (((chr = getchar()) != EOF) && (chr != '\n')); } while (0)
#define SOMELARGESIZE 1024
int main(void)
{
unsigned int index;
unsigned int size;
int result;
fprintf(stderr, "input the desired array size: ");
while (((result = scanf("%u", &size)) != 1) && (result != EOF))
{
fprintf(stderr, "invalid input, try again\n");
clearstdin();
}
if (result == EOF)
{
fprintf(stderr, "EOF recieved, ending the program\n");
return -1;
}
if (size < SOMELARGESIZE)
{
int array[size];
for (index = 0 ; index < size ; index++)
{
fprintf(stderr, "input an integer: ");
if (((result = scanf("%d", &array[index])) == 1) && (result != EOF))
fprintf(stdout, "\tarray[%d] = %d\n", index, array[index]);
else if (result == EOF)
{
fprintf(stderr, "EOF recieved, ending the program\n");
return -1;
}
else
{
fprintf(stderr, "invalid input, try again\n");
index -= 1;
}
clearstdin();
}
}
else
{
fprintf(stderr, "sorry, you requested a very large array\n");
return -1;
}
return 0;
}
上述程序的唯一问题是,如果在scanf()
输入时输入任何空格字符,它将无效,直到有效或无效输入,但特别输入非空白输入
答案 1 :(得分:1)
scanf将返回成功扫描的项目数
如果scanf没有返回1,则读取一个字符并再次扫描scanf
scanf ( "%*[^0-9\n]");
将读取并丢弃任何非数字或换行符。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int i;
int n;
int a[SIZE];
printf("enter number of elements(disks) 0-%d\n", SIZE - 1);
while ( scanf("%d",&n) != 1 || n >= SIZE) {
scanf ( "%*[^0-9\n]");
printf ( "problem with input, try again\n");
}
printf("number was %d\n", n);
printf("enter the elements in ascending order\n");
for(i=0;i<n;i++)
{
while ( scanf("%d",&a[i]) != 1) {
scanf ( "%*[^-0-9\n]");//[^-0-9\n] characters NOT digit, newline or minus
printf ( "problem with input, try again\n");
}
printf("number for a[%d] was %d\n", i, a[i]);
}
return 0;
}