954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

About getchar()

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?

hsp700
Newbie Poster
11 posts since Feb 2010
Reputation Points: 11
Solved Threads: 0
 

You should get a table of ascii characters and look up the character equivalent for 10.

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

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?"

hsp700
Newbie Poster
11 posts since Feb 2010
Reputation Points: 11
Solved Threads: 0
 

>(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.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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.

hsp700
Newbie Poster
11 posts since Feb 2010
Reputation Points: 11
Solved Threads: 0
 

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

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

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)**

hsp700
Newbie Poster
11 posts since Feb 2010
Reputation Points: 11
Solved Threads: 0
 

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 get97. 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 get10

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

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

>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.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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?

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

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;
}
hsp700
Newbie Poster
11 posts since Feb 2010
Reputation Points: 11
Solved Threads: 0
 

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.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

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.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

Thanks jonsca !

hsp700
Newbie Poster
11 posts since Feb 2010
Reputation Points: 11
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You