Friday, July 29, 2016

C Basics - Standard Input-Output in C

C provides a set of built-in functions to perform IO operations. A program can receive input from command line or fetch it from a file. A program can output the data on the computer screen or save it in text or binary files.

C programming treats all the devices as files. The standard files for IO devices are,
Device File Pointer
Keyboard (standard input) stdin
Monitor (standard output) stdout
Monitor (standard error) stderr

The function int getchar(void) reads the next available character from stdin.

The function int putchar(int c) write a character to stdout.

The function char *gets(char *s) reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File).

The function int puts(const char *s) writes the string 's' and 'a' trailing newline to stdout.

The function int scanf(const char *format, ...) reads the input from stdin and scans that input according to the format provided.

The function int printf(const char *format, ...) produces the output according to the format provided and writes that output to stdout.

The format specifier can be %s, %d, %c, %f, etc.

#include <stdio.h>

int main( ) {

   int c;
   char str[100];
   int i;

   printf( "Enter a character :");
   c = getchar( );

   printf( "\nYou entered: ");
   putchar( c ); 
   fflush(stdin);   
   
   printf( "\nEnter a string :");
   gets( str );

   printf( "\nYou entered: ");
   puts( str );
   
   printf( "\nEnter a number followed by a word :");
   scanf("%d %s", &i,str);

   printf( "\nYou entered: %d %s ", i, str);

   return 0;
}
The output of the above program would be:

Enter a character :d

You entered: d
Enter a string :def

You entered: def

Enter a number followed by a word :1 one

You entered: 1 one



Related topics:
File Handling in C   |   Preprocessors in C   |   Header Files in C   |   Type Casting in C   |   Error Handling in C

List of topics: C Programming

No comments:

Post a Comment