' char* strInput =(char*) malloc(sizeof(char));
        int ch;
        int letNum = 0;
        while((ch = getchar()) != EOF){
                letNum++;
                strInput = (char*)realloc(strInput,letNum*sizeof(char));
                *(strInput + letNum - 1) = ch;
        }
        printf("\n");
        printf("%s\n",strInput);
        free(strInput);`

This is the contents of main in a program I wrote that takes an undefined number of chars and prints the final string. I don’t understand why but it only works if I press ctrl+D twice, and only once if I press enter before.

does anyone get what’s going on? And how would you have written the program?

  • @adriator
    link
    41 year ago

    It’s due to the way getchar() and console input work. When you enter “abcdCTRL+D” on the keyboard, here’s what happens:

    • abcd characters are added to the stdin buffer and consumed by getchar()
    • CTRL+D (or EOF on Unix, CTRL+Z on Windows) is left in the input buffer (it’s not yet consumed by getchar()!))
    • The console is waiting for more input, and the next time you press ENTER or CTRL+D the previous one will be consumed by getchar()

    Think about this scenario: What happens if you only enter “abcd” and not press anything else? The program will still be waiting for more input. It needs to receive a signal telling it to stop with the input and proceed with the code execution. But if you press enter, it won’t automatically add a new line to the string, because the new line character is still in the input buffer.

    • @[email protected]
      link
      fedilink
      21 year ago

      This guy is right. I saw OP’s post but I did not have enough time to reply at the time. I came back to reply to OP’s post, but you are already right.

    • @[email protected]OP
      link
      fedilink
      11 year ago

      Thanks a lot for your answer. This might be because of my shallow understanding of how a buffer works, but I don’t understand why EOF isn’t consumed by getchar() when the other bytes are consumed. Isn’t a char just a number and EOF too (-1 I think)? I probably should try and understand buffers more

      • @adriator
        link
        11 year ago

        When you press CTRL+D, first a signal is sent to the console to stop reading from the keyboard, then the EOF character gets added to the buffer. That’s why it is not consumed at the same time as the previous characters.