1
votes
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

5 Answers

9
votes

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.

5
votes

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++;
}
1
votes

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++;
                }
        }
} 
1
votes

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
votes

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++;
}