Saturday, September 10, 2011

differnce between getc() and getchar()


C/C++ Run-Time Library Functions


Format
#include <stdio.h>
int getc(FILE *stream);
int getchar(void);
Language Level: ANSI
Threadsafe: No. #undef getc or #undef getchar allows the getc or getchar function to be called instead of the macro version of these functions. The functions are threadsafe.
Description
The getc() function reads a single character from the current stream position and advances the stream position to the next character. The getchar() function is identical to getc(stdin).
The difference between the getc() and fgetc() functions is that getc() can be implemented so that its arguments can be evaluated multiple times. Therefore, the stream argument to getc() should not be an expression with side effects.
Return Value
The getc() and getchar() functions return the character read. A return value of EOF indicates an error or end-of-file condition. Use ferror() or feof() to determine whether an error or an end-of-file condition occurred
Example that uses getc()
This example gets a line of input from the stdin stream. You can also use getc(stdin) instead of getchar() in the for statement to get a line of input from stdin.
#include  <stdio.h>
 
#define LINE 80
 
int main(void)
{
  char buffer[LINE+1];
  int i;
  int ch;
  printf( "Please enter string\n" );
 
  /* Keep reading until either:
     1. the length of LINE is exceeded  or
     2. the input character is EOF  or
     3. the input character is a new-line character
   */
 
  for ( i = 0; ( i  < LINE ) && (( ch = getchar()) != EOF) &&
               ( ch !='\n' ); ++i )
    buffer[i] = ch;
 
  buffer[i] = '\0';  /* a string should always end with '\0' ! */
 
  printf( "The string is %s\n", buffer );
}
getchar is for inputting a single character and it returns a value (character)



No comments:

Post a Comment