c:如何用信号通知输入结束 [英] c : How to signal end of input
问题描述
在这个提示用户输入多项式的简单程序中,
in this simple program that prompts users to input a polynomial,
我将int 999用作代表输入结束的值.
I used int 999 as a value that represents end of input.
但是,这不是一个好的设计,因为用户将无法输入系数为999的多项式节点.
However, this is not a good design because users will not be able to input a polynomial node with a coeff of 999.
是否存在可以唯一表示输入结束的替代键?
Is there an alternative key that can be unique to represent end of input?
相关代码:
int coeff;
int expon;
int i = 1;
printf("\nInput for polyNode %d (999 for exit):",i);
printf("\n\tInput coeff : ");
scanf("%d",&coeff);
while(coeff != 999)
{
printf("\tInput expon : ");
scanf("%d",&expon);
insertBack(&polynomial, &polynomialRear, coeff, expon);
i++;
printf("\nInput for polyNode %d (EOF for exit):",i);
printf("\n\tInput coeff : ");
scanf("%d",&coeff);
}
printPoly(polynomial);
printf("\n");
推荐答案
您可以检查scanf的返回值.如果扫描成功,在这种情况下,将为扫描的一项返回1.如果扫描不成功,它将返回0或EOF.输入任何非整数值(字母...)将结束while ( 1)
循环.
然后在一个while循环中使用getchar()
清除输入流.
You can check the return of scanf. If the scan is successful it will, in this case, return 1 for one item scanned. If the scan is unsuccessful, it will return either 0 or EOF. Input of any non-integer value (letters...) will end the while ( 1)
loop.
Then clear the input stream with getchar()
in a while loop.
int coeff;
int expon;
int i = 1;
while(1)
{
printf("\nInput for polyNode %d :",i);
printf("\n\tInput coeff : ");
if ( ( scanf("%d",&coeff)) != 1) {
break;
}
printf("\tInput expon : ");
if ( ( scanf("%d",&expon)) != 1) {
break;
}
insertBack(&polynomial, &polynomialRear, coeff, expon);
i++;
}
while ( ( i = getchar ()) != '\n' && i != EOF) ;//clear input stream
printPoly(polynomial);
printf("\n");
这篇关于c:如何用信号通知输入结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!