Skip Navigation

Lessons of "== 0/1/EOF" versus "!= 0/1/EOF" and scanf() versus getchar() in while loops

I was experimenting with while loops, testing what happens if I condition the loop with == 0/1/EOF versus != 0/1/EOF. Obviously, this shows, more than anything else, my lack of understanding of the logic behind these operations, but it also taught me that getchar() will return the ASCII value of chars and ints if I use the format specifier %d. Also, that scanf() isn't as "forgiving", causing infinite loops, among other things, if I under certain conditions enter a char.

Is there anything else that I could learn/take away here, or was this a waste of time? 😅

The various results are commented next to the respective loops.

   
    
#include <stdio.h>  

int main() {  

	int number = 0;  

	printf("Enter a number: ");  

/*  
	while((scanf("%d", &number)) != 1) { //Success with "== 1" or "!= 0/EOF", terminates after int input with "== 0/EOF" or "!= 1", terminates after char input with "== 1" or"!= 0", infinite loop after char input with "== 0" or "!= 1/EOF".  
		printf("You have entered number %d\n", number);  
		printf("Enter a new number: ");  
	}  
*/  

/*  
	while ((number = getchar()) == EOF) { //Success with "!= 0/1/EOF", terminates after input with "== 0/1/EOF".  
		getchar();  
		printf("You have entered number %d\n", number);  
		printf("Enter a new number: ");  
	}  
*/  

	return 0;  
}  


  

Comments

2