can anyone explain why this code works?

+1 Hayden Kuk · November 16, 2015
I am currently reading a book called C programming : modern approach

there is a code as following :

int main()
    char ch;
    int len = 0;
    printf("Enter a message: ");
    ch = getchar();
    while( ch != '\n')
        ch = getchar();
    printf("Your message was %d character(s) long.", ch);

    return 0;

I really wonder how putting 'getchar' in this code makes it possible to properly execute while loop.

Post a Reply


Oldest  Newest  Rating
+2 Jon Z. · November 16, 2015
Basically it reads an input char and returns it, and '\n' is new line (enter key).
So every time that a char is entered, but it's not '\n' it adds 1 to the variable len.
+1 Dan P · November 20, 2015
The problem with the code above is this line,

printf("Your message was %d character(s) long.", ch);

You are saying, print the decimal value of the ch char. As you can only exit the loop by entering a newline character
it will always be 10, as 10 is the ascii value for newline.

Changing the line to this will give you a working example.

printf("Your message was %d character(s) long.", len);

Although, this will only tell you how many visible characters there are, it is not telling you about the newline character that exists.
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator