Friday, February 5, 2016

C Input and Output Statements

 Input/output statements defines how we can read input from different input devices or write into different output devices. By input operation, we mean user providing values for the program through an external device (like keyboard) and by output operation, we mean writing results of computation to an external device, like monitor, printer etc. An input/output statement is nothing but standard function provided by C and each of them have a list of arguments enclosed in parentheses.

Standard Input/ Standard Output/ Standard Error

When you run a C program, operating system opens 3 files and provides it to the program; they are standard input, standard output and standard error.
  1. Standard input file is used to take inputs to the program provided by user. Standard input device is your keyboard.
  2. Standard output file is used to write the output that your program creates. Standard output device is your monitor.
  3. Standard error file is used to write the errors encounter during program execution. Your monitor serves as the standard error file.

    Character Input/Output

    As mentioned in the earlier chapters, character data type can holds only one character. To read a single character data type from the input device, C has getchar() function. The function can be used as given below
    char c = getchar();
    Here c is a character variable. This function will wait for one input character, read it when it's available from standard input device (like a keyboard) and assign it to the variable (here 'c').
    We can write a single character to the standard output device (like a monitor) using another standard function provided by C called putchar(). This function can be used as given below
    putchar(c);
    Here 'c' is a character variable and its content will be written to the output device.

    Example of Character Input/Output

    1. #include<stdio.h>
    2. void main()
    3. {
    4. char c;
    5. printf("Enter a character: ");
    6. c = getchar();
    7.  
    8. printf("You have entered:");
    9. putchar(c);
    10. }
    11.  
    12. Output:
    13. Enter a character: b
    14. You have entered: b
    The above program will wait for you to enter a character at line 6. Once you've entered it, program reads it from the keyboard and writes it back into the monitor.

No comments: