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;  
}  

  • CameronDev@programming.dev
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    10 days ago

    man scanf:

    RETURN VALUE
           On success, these functions return the number of input items successfully  matched
           and  assigned;  this can be fewer than provided for, or even zero, in the event of
           an early matching failure.
    

    man getchar:

    RETURN VALUE
           fgetc() and getchar() return the character read as an unsigned char cast to an int
           or EOF on end of file or error.
    

    There are a lot of inconsistencies with C functions, so important to check the man pages so you can handle them correctly.

    Your call to getchar isn’t quite correct either, pressing the 1 key would print out 49, which is the ASCII codepoint for the 1 char.

    • printf("%s", name);@piefed.blahaj.zoneOP
      link
      fedilink
      English
      arrow-up
      2
      ·
      edit-2
      10 days ago

      Ah, forgot about those. Thanks! On Linux, I read man pages all the time. Need adopt that same rutine.

      Regarding getchar() returning the ASCII code of the input, I commented this is the OP:

      getchar() will return the ASCII value of chars and ints if I use the format specifier %d.