1

I've just begun to learn C and I've got a problem with some basic code. according to the book i'm reading (C Programming Language) this code should accept user input and then output it. Instead im just getting the first letter of the input before the program closes

#include <stdio.h>

main()
{
    int c;

    c = getchar();
    while (c != EOF) {
        putchar(c);
        c = getchar();
    }

}
b9703
  • 107
  • 2
  • 11
  • 4
    you should use `int main`, because implicit-int is outdated. Also, return 0 at the end. – lost_in_the_source Mar 20 '16 at 13:35
  • Try redirecting input so it is read from a file. When input is echoed to the same device as output is written (e.g. a screen) you won't necessarily see everything you expect. – Peter Mar 20 '16 at 13:37
  • 4
    How *exactly* are you running this? The code looks correct, contrary to consensus below. This *will* line buffer stdout, so you won't see any output until you enter a cr/lf, but if you type "blah" and hit enter, you should see "blah" afterward. – WhozCraig Mar 20 '16 at 13:41
  • I run it at https://ideone.com/qh3tak successfully. And yes WhozCraig is right, it is functionally the same code. Actually, the code is very much correct (it is an example from Kernighan & Ritchie). So the problem must be in the OP's IDE. – Dimitar Mar 20 '16 at 13:43
  • Are you on win OS? – Frankie_C Mar 20 '16 at 14:26
  • @stackptr Since C99, return 0 is not necessary. See http://stackoverflow.com/a/8677691/5399734 – nalzok Mar 20 '16 at 14:33
  • Is that the *exact* code you're running? Though it's a bit outdated (and invalid as of C99), if it compiles it should work correctly -- and it works fine for me. How exactly are you running it? What OS are you using? – Keith Thompson Sep 08 '16 at 21:43
  • The OP commented on a now-deleted answer that he's using codeblocks (that shouldn't make any difference). Code::Blocks runs on Linux, Windows, and MacOS, so that doesn't tell us much about the platform. The OP hasn't been seen on Stack Overflow in about 2½ weeks, so we shouldn't expect quick feedback. – Keith Thompson Sep 08 '16 at 22:35
  • could you post a sample output? – Pushan Gupta Oct 04 '17 at 17:51

1 Answers1

0
#include <stdio.h>

main()
{
    int c;
    c = getchar();
    while (c != EOF) {
        putchar(c);
        c = getchar();
    }
}

Works correct.

Understand the basic concept of getchar:- getchar is a function in C programming language that reads a single character from the standard input stream stdin, regardless of what it is, and returns it to the program.

The main Problem must lie with the IDE.

Simon Prickett
  • 3,838
  • 1
  • 13
  • 26