Question

I am testing a simple program in C:

int main() {
    int c;

    c  = getchar();

    while ( c != EOF ) {
        printf("%c\n", c);
        c = getchar();
    }
}

However, when I give simple inputs like 'a', 'b', it print out "a\n\n, b\n\n"... Can someone please explain? Thank you!

☛  gcc hello.c; ./a.out
a
a


b
b


c
c
Was it helpful?

Solution

Because it's getting the EOL character as well as the one you type.

Your input isn't 'a', 'b', it's 'a\nb\nc\n', and your script is configured to (basically) output a new line after every character.

So the first time through the loop, it gets 'a' and prints 'a\n', then it gets '\n' and prints '\n\n'. Then 'b' and 'b\n', etc.

Try this on for size:

int main() {
    int size = 500;
    char buff[size];
    char* check;
    int read;


    check = fgets(buff, sizeof(buff), stdin);

    while ( check != NULL ) {
        printf("%s", buff);
        check = fgets(buff, sizeof(buff), stdin);
    }
}

OTHER TIPS

Look at the code

 printf("%c\n", c);

That says to print out the character and then a newline. That is in addition to echoing the input which has a character and a newline.

You may want to shut off character echoing for interactive use. Or just read the input from a file.

After you enter a character and press enter, the '\n' newline character is still left in the input stream, and you pick it up with the second getchar();

So your printf prints out a newline character and then prints another one because it picked up the newline character.

getchar() gets one character from input buffer. By default, input mode is line-buffered ("canonical" mode), meaning you enter "a" followed by Enter/Return key press, and only after that data is put into input buffer, which results in two chars added to input buffer: "a" char itself and "\n" char corresponding to Enter/Return key.

Different operating systems have different methods of switching to unbuffered ("non-canonical") mode, if you need it. This is some ioctl() or tcsetattr() magic on UNIX/Linux systems, and SetConsoleMode() on Windows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top