Reading input from getchar

2k Views Asked by At
while(1)
{
    if(i == 6)
        break;
    temp[i] = getchar();
    putchar(temp[i]);
    i++;
}

Whenever i had to use getchar in this way, it accepts enter also as one of the input and thus I am restrained to enter only three characters instead of 6. Why getchar takes enter as one of the input? How to avoid this?

Input:

1
2
3

After this loop breaks because the three returns pressed are considered as three inputs to temp[1], temp[3] and temp[5].

5

There are 5 best solutions below

0
On

getchar reads one character at a time from the stdin buffer. once you are entering a character and pressing Enter then in stdin buffer two characters are getting stored.

if you want to enter six character by using your code then enter all characters at once and then press enter it will work. otherwise you will have to skip 'Enter' character. like this...

#include<stdio.h>
int main()
{
        int i=0;
        char temp[10];
        while(1)
        {
                if(i == 6)
                        break;
                temp[i] = getchar();
                if(temp[i]!='\n')
                {
                        putchar(temp[i]);
                        i++;
                }
        }
} 
0
On

Why getchar takes enter as one of the input?

The character input functions read input from a stream one character at a time. When called, each of these functions returns the next character in the stream, or EOF if the end of the file has been reached or an error has occurred. Some character input functions are buffered (Example: getchar()). This means that the operating system holds all characters in a temporary storage space until we press Enter , and then the system sends the characters to the stdin stream.

How to avoid this? As suggested by haccks

0
On

how about this method.You can use getchar() two twice. Like this,

while(1)
{
    if(i == 6)
        break;
    temp[i] = getchar();
    getchar();
    putchar(temp[i]);
    i++;
}
3
On

getchar reads a character at a time. On pressing Enter key you are passing newline character \n to the C standard buffer, which is also read by getchar on next call of getchar. To avoid this \n character you can try this

while(1)
{
    if(i == 6)
        break;
    if((temp[i] = getchar()) != '\n')
    {
        putchar(temp[i]);
        i++;
    }
}   

Also read this answer to know how getchar works.

0
On

Check for white space character and don't add/count it. getchar() returns all characters you hit including new lines and spaces.

while(i < 6)
{
    temp[i] = getchar();
    if (isspace(temp[i]))
        continue;

    putchar(temp[i]);
    i++;
}