Reputation: 167
in this simple program that prompts users to input a polynomial,
I used int 999 as a value that represents end of input.
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?
Relevant Code :
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");
Upvotes: 3
Views: 3346
Reputation: 8286
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");
Upvotes: 1
Reputation: 866
You can wait till end character will arrive, it maybe any symbol you wish (not a number, CRLF, TAB etc). After receiving of a complete input string do a processing.
Upvotes: 0