This could help Flush the input buffer
Printable View
This could help Flush the input buffer
-reading what getchar does I am puzzled how this while loop solved my problems. I declared int ch; in program also. This loop seems to clear out string from previous if statement. Can someone explain why this works now? I am using link you posted above but still confused.Code:84 if (scanf("%d", &nfl.points) != 1)
85 printf("Please try again\n");
86
87 while ((ch = getchar()) != '\n' && ch != EOF);
88 {
89 if (scanf("%d", &nfl.yards) != 1)
90 printf("Please try again\n");
91 }
Well I am guessing it just verifies there is data in stdin and overwrites those contents??
-Also how could I add code to make user enter a correct number instead of using printf and exiting with no valid input?
And more importantly utilize the quotee below:
Do I just assign buff = nfl.points and then see ifisdigit?Quote:
fgets( buff, BUFSIZ, stdin );
Then validate buff in whatever way you choose, and copy the data to it's final destination.
if user pesses something like
qw<ENTER>
scanf("%d"...
will not be able to read anything from the stream leaving 3 chars there
'q' , 'w' , '\n'
while loop added just reads all chars till it encounters \n - leaving stdin empty
so probably your alltogether loop should be
Code:while(scanf("%d",&nfl.points) != 1)
{
/* clean the stdin */
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
/* and try again */
printf("Please try again\n");
}
/* succesfully read nfl.points number - could continue*/
no, if you want to use fgets approch - it will be likeQuote:
Do I just assign buff = nfl.points and then see ifisdigit?
Code:char buffer[BUFSIZ];
char* res;
while((res = fgets(buffer,sizeof buffer, stdin)) != NULL)
{
if(sscanf(buffer, "%d" , &nfl.points) != 1) /* we can use strtol to make more carefull testing of the user input */
{
/* successfully read number */
break;
}
/* line format was incorrect */
printf("Please try again\n");
}
if(res == NULL)
{
/* fgets failed - probably EOF riched - need to abort */
return -1;
}
/* successfully read number - we can continue */
I will add to my program both methods you explained. Thanks for the help!
Works very well. Thanks again!
do not mix fgets and scanf in the same program - stick to one method - or read everything with fgets and then convert
or use scanf - without need for convert...
mixing them could bring unexpected bugs in your code due to scanf leaving \n in stdin and next fgets reading it instead of the next string...
Should this be ok?
Code:95 printf("Please enter total points\n");
96 while(scanf("%d",&nfl.points) != 1)
97 {
98 /* clean the stdin */
99 while ((ch = getchar()) != '\n' && ch != EOF);
100
101 /* and try again */
102 printf("Please try again\n");
103 }
104
105 printf("Please enter total yards\n");
106 while(scanf("%d",&nfl.yards) != 1)
107 {
108 /* clean the stdin */
109 while ((ch = getchar()) != '\n' && ch != EOF);
110
111 /* and try again */
112 printf("Please try again\n");
113 }