2

While trying different things with getchar I figured out that it usually only safes on character in an variable. Somehow when I use a while loop the behaviour changes and it returns more characters if the input is more than one.

Here is my example code for "normal" behaviour. putchar() return only one character even more are put in:

#include <stdio.h>

main() {
    char c;

    printf("Type a character in here: ");
    c = getchar();
    printf("You just typed : ");
    putchar(c);
    
}

Somehow when I want to use it in a while loop the putchar() function returns more than one character if more are put in:

Here is the second part:

#include <stdio.h>

void print_input();

main() {
    char c;

    printf("Type a character in here: ");
    c = getchar();
    printf("You just typed : ");
    putchar(c);

    print_input();  
}


void print_input() {
    char ch = 'x';
    while (ch != '#') {
        ch = getchar();
        putchar(ch);
    }
    return;
}

Additional question: While running this in debugger the behaviour somehow is different than if I try this in runtime. Why is that so?

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
Nizde
  • 21
  • 2
  • 2
    Please give the exact input, expected result and actual result. `getchar` will certainly not return more than one character. So you need to clarify the exact behaviour you are seeing. – kaylum Sep 01 '21 at 20:34
  • Maybe unrelated, but you should not be assigning the return value of `getchar` to a `char`, natural though it might seem. Read https://stackoverflow.com/questions/35356322/difference-between-int-and-char-in-getchar-fgetc-and-putchar-fputc – Nate Eldredge Sep 01 '21 at 20:38
  • Why is it unusual that if `getchar` and `putchar` are called multiple times (in a loop), multiple characters are read and printed? The behavior should be identical in or outside of a debugger, unless the invalid `main` signature causes UB. – Yun Sep 01 '21 at 20:39
  • 7
    Just to state the obvious, `getchar()` returns only a single character each time it is called, or else the value `EOF` which is not a character. If you think it is somehow returning several characters at once, then you are misinterpreting your observations. But until you explain what you actually observe, we won't be able to help you clear up that misinterpretation. – Nate Eldredge Sep 01 '21 at 20:44
  • 2
    `getchar()` will return one character at a time from your line buffer after you've pressed return. Your program will loop and `getchar()` until the line buffer is empty and then wait for new input. Is that what you are observing and misinterpreting? – Ted Lyngmo Sep 01 '21 at 20:46
  • @kaylum: Re “`getchar` will certainly not return more than one character.”: Sure it will, all you have to do is call it more than once. If a problem statement does not appear to make sense at first, try to have a broader interpretation. – Eric Postpischil Sep 01 '21 at 20:49
  • 1
    In fact guys, after testing it step by step and printing empty lines in between the getchar and putchar the loop is iterating throw the line buffer. – Nizde Sep 01 '21 at 20:51
  • What do you mean by "throw the line buffer"? Can you please [edit](https://stackoverflow.com/posts/69020267/edit) the post to update it with the exact input and output? – kaylum Sep 01 '21 at 20:52
  • @Nizde I guess "_throw_" should be _through_? – Ted Lyngmo Sep 01 '21 at 20:53
  • Perhaps you are thinking that `getchar` will return immediately after a character is entered. That is not the case - `stdin` is by default line buffered and `getchar` will not return until a newline is entered. At that point it will get one character but more characters will be available in the line buffer for subsequent `getchar` calls to read. – kaylum Sep 01 '21 at 20:55
  • My interpretation of getchar and putchar was that getchar is requesting me to input some character and then only taking the first one and giving it back with putchar. Why is the getchar and putchar programm iterating through the buffer in my while loop? I would expect that after getchar and i put in more characters it just saves the first one and gives only the first one back. With putchar i would await the first character. In the next iteration i would expect getchar to request me to input again sth. – Nizde Sep 01 '21 at 20:56
  • 1
    @Nizde Well, it doesn't work according to your expectations. – Ted Lyngmo Sep 01 '21 at 20:57
  • Example of what i expected: "First round getchar: I put in 'asd' putchar: returns 'a' "Second round getchar: Requests and I put in 'gda' putchar: returns 'gda' But what happens is: "First round: getchar: I put in 'asd' putchar: returns 'a' "second round: getchar: Take automatically 's' putchar: returns 's' "third round: getchar: takes automatically 'd' putchar: returns 'd' "fourth round: getchar: requests now again new input – Nizde Sep 01 '21 at 20:58
  • @Nizde Yes, that is how it's supposed to work. – Ted Lyngmo Sep 01 '21 at 21:00
  • 1
    Ok Guys, now I understand how getchar is working. Thanks alot for all your fast responds! :) – Nizde Sep 01 '21 at 21:00
  • 1
    getchar() doesn't return any characters: it returns an int. – Lee Daniel Crocker Sep 01 '21 at 21:14
  • @LeeDanielCrocker right but the number is than representative for a character? Since the code is working i asume that the compiler is turning the int value in a character automatically? Is there any good practice that gives a better way of working with this? Maybe using "int" instead of "char" and casting that later to "char"? I am still learining so feel free to improve my atempt with explanation. :) – Nizde Sep 01 '21 at 21:52
  • 1
    getchar() returns an int. This can be either the integer value EOF, which is guaranteed not to be the value of any valid character (it's usually -1), or it can be the value of a character (ints are bigger than chars, so an int can hold any char plus lots more). – Lee Daniel Crocker Sep 01 '21 at 22:24
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 05 '21 at 00:22

1 Answers1

1

When you enter multiple chars and hit enter, the program will see that whole input (because it's line buffered). So multiple calls to getchar will return subsequent characters and remove them from the stream:

Try to play with this:

char c;
char d;

printf("Type chars in here: ");
c = getchar();
d = getchar();

printf("C: %c \n", c);
printf("D: %c", d);

This is duplicated with: How is the "getchar()" function able to take multiple characters as input?

You can read more there.

Suciu Eus
  • 169
  • 1
  • 8
  • 1
    getchar() returns an int. You can't use a char variable to hold its value. – Lee Daniel Crocker Sep 01 '21 at 21:14
  • @Suciu Eus: I get your point and i quess this is what i didnt understand in the beginning. It seems that I have to spend some time to understand the stdin lib and how streams work. Thank you for your answer! :) – Nizde Sep 01 '21 at 21:41
  • @LeeDanielCrocker: There is nothing wrong with converting the `int` return value of `getchar` to a `char`, provided that the value is not `EOF`. When dealing with user input, it is rather safe to assume that the value is not `EOF`. (Of course, a robust application should not make the assumption that it is dealing with actual user input and should also take the possibility into account of the user entering `EOF`). – Andreas Wenzel Sep 01 '21 at 22:26
  • @LeeDanielCrocke Unless it's EOF, `getchar()` returns an unsigned char converted to an int. But that's not the point of the example – Suciu Eus Sep 02 '21 at 07:16