Friday, May 21, 2010

C Programming scanf?

do


{


printf("Enter day and leap year codes (ex. 4 0): ");


scanf("%i %i", %26amp;dayStart, %26amp;leapYear);


printf("\n");





}while((dayStart %26gt; 6 || dayStart %26lt; 0) %26amp;%26amp; (leapYear != 0 || leapYear != 1));





This is the menu portion of my program and basically i want the program to loop and ask the user for information IF the user fails to enter the data in correctly





dayStart must be between 0 - 6


leapYear must be 0 or 1





The program works if i enter in interger numbers however if i enter in a character the program proceeds to do an infinate loop. Could someone tell me what i'm doing wrong?





Thanks

C Programming scanf?
The problem is that scanf actually returns a value signifying HOW the scanning went.





The function returns the total number of items successfully read, EOF when the input stream reached its end, or a negative number if an error occurs.





When an error happens, the input buffer is NOT flushed, ie the next call to scanf will read the exact same data as the previous call worked.





The normal solution wopuld be to check the return value from scanf, and if it is less than 0 do a read of the input buffer by using a


gets(a_line)


call whete a_line has been declared as an array of characters.





char a_line[100]; gets(a_line);
Reply:change


while(dayStart %26gt; 6 || dayStart %26lt; 0) %26amp;%26amp; (leapYear != 0 || leapYear != 1)


to while(dayStart %26lt; 6 || dayStart %26gt; 0) %26amp;%26amp; (leapYear != 0 || leapYear != 1)


then it works
Reply:Change the scanf to use %c so that you can get the characters. Then, once you receive the input, test them for being valid.


No comments:

Post a Comment