Search code examples
cloopsfor-loopgetchar

c programming enter character for loop


I am trying to write a simple code.

I should enter 10 letters using getchar and after print the smallest.

Ex. 'A' is 65 in ASCII and if I enter 'A', it should print that 'A' is smallest.

I have done the first part where I should enter the letters and something in my for loop is breaking.

This is my code:

#include <stdio.h>

int main(void) 
{
    char ch;
    int i;

    for(i=0; i<10; i++) {
        ch = getchar;
        printf("You entered : %c\n", ch);
    }

    return 0;
}

Using the program I get this five times:

a
You entered : a
You entered : 

Solution

  • It's not exactly clear what you're asking, I'm assuming you're wondering why your program stops after what seems to be 5 iterations and why you are getting the empty extra You entered:.

    This is due to the way getchar() works. When you input a charecter and press Enter you're actually inputting something like a\n. The first time getchar runs it grabs the a and the second time it grabs the n (new line) taking two iterations. Once it does this then it waits for you to input more because it's consumed the entire input it had available.

    One solution for your problem is to use an extra getchar() after ch = getchar() that you don't assign to anything in order to consume the extra newline.

    More discussion on this is available in this question.