0

I'm a newbie to C and I know that Char type variables can only hold one character - something like

char c = 'a';

If this is true, how does this C program I wrote work?

#include "stdafx.h"
#include <stdio.h>


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

    getchar();
    return 0;
}

If you follow the example, variable c is a char, so it can only hold one character, but when I the program, I can type a whole string like "Hello world" into the console, and after I hit Enter (I know that the getchar() function will assign what i've typed in to variable c), the console prints a whole string like "Hello world" too (that's what the putchar() function does.) I ran this code in Visual Studio 2010.

What I thought is that when I type the string "Hello world" and type enter, the program must give a warning because an overflow happened. Nevertheless, when I enter a string over the size limit of a char type (1 byte length) everything runs fine. Why is there no error?

Owen Versteeg
  • 342
  • 2
  • 14
  • 5
    It only holds one character at a time. Of course variables can change; that's what "variable" means. – Wooble Feb 10 '14 at 11:17
  • it mean that when i type anything, getchar() run and imediately, putchar() must print what i type, but it's not – user3292459 Feb 10 '14 at 11:20
  • 1
    You type the whole string, the first getchar() get first character, the remaining string stay at input stream, and your later getchar() inside while loop read them(one by one) and print out(one by one) until there are no char left(EOF), that's what happen. – moeCake Feb 10 '14 at 11:22
  • getchar reads buffered input, so it blocks waiting for you to finish the line. – Wooble Feb 10 '14 at 11:24
  • 2
    For future reference: When using `getchar()` and `EOF`, use `int c`. `getchar()` returns 257 different values, 0-255 and EOF. – chux - Reinstate Monica Feb 11 '14 at 22:32
  • Also for future reference: Welcome to StackOverflow! Your status suggests you have not yet read the [About Page](http://stackoverflow.com/about); please do so at your convenience. You might want to mark an answer you like as "Answered". – Jongware Feb 11 '14 at 22:46

1 Answers1

1

Your assumption of what the getchar() function does is wrong.

int getchar ( void );

This code returns the next character from standard input (stdin)

int putchar ( int character );

This code writes a character to the standard output (stdout).

Check these links:

getchar and putchar

Plus (as was noted in the comments) getchar reads buffered input so it waits until you hit enter.

If you want to write without waiting for enter check this.

Community
  • 1
  • 1
qwr
  • 3,660
  • 17
  • 29