Hi, I am trying to understand the Standard C function "getchar()".
I am using CodeBlocks 8.02 in Windows XP.
Please compile this code in your compiler and note how it behaves:

#include<stdio.h>

int main()
{
    int i=getchar();
    while(i!=9)
    {
        printf("%d",i);
        i=getchar();
    }
    printf("%d",i);
    return 0;
}

When I insert Tab, it prints "9" and terminates.

But when anyother character is inserted it prints ascii value of that character
+ ascii value of '\n' (10)!
e.g. If I insert "a", it prints "9710"!
Why it prints "10" too?

when I insert more than one characters, it prints ascii values of all that characters + ascii value of '\n' (10)!
e.g. If I insert "a b", it prints "97329810"!

Why? Can anyone please explain how this happens?

Character equivalent to 10 is (NL line feed, new line) according to
asciitable.com.
When I press the key on which "Enter" is printed (the key of keyboard which we use to go to new line while typing), the code I have given prints "10". It means 10 is ascii value of "Enter" key. But this is not my question!!

The questions are:
(1) "(when we insert one character)Why code prints "10" after printing ascii value of the character we insert?"

and
(2) "(when we insert more than one characters)Why(& How?) code
prints ascii values of all that characters and "10" after them?"

>(1) "(when we insert one character)Why code prints "10"
>after printing ascii value of the character we insert?"

Because you actually typed two characters? You press the 'a' key right? Then you press then [Enter] key, right? That's two characters: 'a' and newline.

I'd love to hear why you think you only "inserted" N-1 characters when you clearly pressed N keys on your keyboard.

Hey! I also thought exactly what you are saying!!
But......but.........but!!!!!!!!!!

Remove while loop from the code I have given in my first post, now
code will look exactly like the code given below:

#include<stdio.h>

int main()
{
    int i=getchar();
    printf("%d",i);
    return 0;
}

Please compile this code and note its behaviour, It behaves
"absolutely normal".

When I insert "a", it prints "97"(NOT "9710"!),
When I insert "a b", it prints "97"(NOT "97329810"!).
Also in this code I press "Enter" to insert character, but getchar() function takes just one character(the character which we type first).

Thats why I still cannot understand the code which I have given in my first post of this thread. I have heard that C is a cryptic
language, and some parts of it (like this one!) make me feel it true.

So? You leave the \n in the buffer and exit? What does that prove? Try typing "abcdefgh". What happens?

The code I have given in my first post of this thread:

#include<stdio.h>

int main()
{
    int i=getchar();
    while(i!=9)
    {
        printf("%d",i);
        i=getchar();
    }
    printf("%d",i);
    return 0;
}

During this code's(which has while loop) execution
when I type "abcdefgh", it prints "97989910010110210310410".

Remove while loop from the code, it will look exctly like the
code given below:

#include<stdio.h>

int main()
{
    int i=getchar();
    printf("%d",i);
    return 0;
}

During this code's(which does not have while loop) execution
when I type "abcdefgh", it prints "97". In other words it behaves
normally

**In these both codes I press "Enter" to insert character(s)**

Edited 6 Years Ago by hsp700: n/a

Read very carefully. Turn off the TV, turn off the radio. Study this post.

When you enter anything into an input, each and every key you press (except the obvious CTRL, ALT, etc) is a character. Including the ENTER/RETURN key! You type in a and hit ENTER, you have 2 (two, dos, deux...) characters in the buffer.

You now use getchar() . How many characters does it read? 1 (one, uno, un). You output the character read, you get 97. That leaves the ENTER in the buffer.

If you exit, you leave that ENTER in the buffer. You loop, the getchar() reads the ENTER. You output the character read, you get 10

Any more questions? If so, you'll just have to believe us.

>I have heard that C is a cryptic language, and
>some parts of it (like this one!) make me feel it true.

There are parts of C that can be confusing, but this isn't one of them. getchar reads one character from the stream. Let's say the stream contains "abcdef\n". If you call getchar once, you'll get 'a'. Call it again and you'll get 'b'. Keep calling it and eventually you'll get '\n'.

'\n' is just another character that gets pushed onto the stream when you press the [Enter] key. Your results from the test programs are exactly what I'd expect.

Try this version of your code:

#include<stdio.h>

int main()
{
    int i=getchar();
    while(i!=9)
    {
         if (i >= 32 && i < 127) 
        {
            printf("The character '%c' (%d) was entered\n",i,i);
        }
        else
        if (i == 10) 
       {
            printf("The ENTER key (%d) was pressed \n",i);
       }
        else
       {
            printf("A weird character was pressed (%d)\n",i);
       }
        i=getchar();
    }
    printf("%d",i);
    return 0;
}

Does this help?

The reason I started this thread is to understand getchar() function
perfectly. I still do not understand it perfectly but after studying
your (WaltP & Narue) posts I understand it much better than
before, Thank you.

#include<stdio.h>

int main()
{
    char line[80];
    int i=0;
    line[i]=getchar();
    while(line[i]!='\n')
    {
        i++;
        line[i]=getchar();
    }
    line[i]='\0';
    printf("\n%s",line);
    return 0;
}

Isn't the code given above equal to the code given below?:

#include<stdio.h>

int main()
{
    char line[80];
    scanf("%[^\n]",&line[0]);
    printf("\n%s",line);
    return 0;
}

Edited 6 Years Ago by hsp700: n/a

The key to this situation is that even when you are not using getchar within a loop the extra '\n' is still in the input stream.
Since you are not accessing the stream again it just becomes a distant "memory" as your program finishes.
Compare that to when you are going through the loop for the nth time the '\n' character is still hanging around and gets read in.

What I had also meant to say (I ran out of edit time) was the the others have explained it very well but this is just my 0.02.

This article has been dead for over six months. Start a new discussion instead.