C Standard Input output functions

In this lesson, we discuss C standard input output functions that help us receive data from the input or print the data on the screen. C language comes with a standard library called “stdio.h” which contains these functions. In the following, we will go through some of them.

C standard input functions

To receive data from the input(keyboard), we have a bunch of standard functions in C language:

The getchar() function

The “int getchar(void)” reads the next available character from the screen and returns it as an integer. This function can read only one character each time. To read more characters, you can use the combination of a loop and this function. Look at this example:

#include <stdio.h>

int main(){
    int character;
    printf("Enter a character: ");
    character = getchar();
    
    return 0;
}

The gets function

The “char *gets(char *s)” function reads a line from the input until a terminating newline. Check this example:

#include <stdio.h>

int main(){
    char string[20];
    printf("Enter a string: ");
    string = gets();
    
    return 0;
}

The scanf() function

The “int scanf(const char *format, …)” function reads the input according to the format privided.

#include <stdio.h>

int main(){
    char str[20];
    int x;

    printf("Enter a string and an integer: ");
    scanf("%s %d", str, &x);
    
    return 0;
}

The above code checks the input, so when the user types some characters and hits enter, scanf() function expects to receive a string, then an integer. This function stops when it sees a space after the expected format. Therefore, “Hello 10 world” is cut after 10.

C standard output functions

To send data to the screen, we have a bunch of standard functions in C language:

The putchar() function

The “int putchar(int c)” prints the input character on the screen and returns the same character. This function is suitable for printing single characters on the screens. In case combined with loops, can print more than one character. Look at the following example:

#include <stdio.h>

int main(){
    char str[] = "Hello";
    putchar('H');
    putchar('\n');

    for(int i=0; i<5; i++)
        putchar(str[i]);
    
    return 0;
}

The result is:

H
Hello

The puts() function()

The “int puts(const char *s)” prints the string s and a newline on the screen. Take this example:

#include <stdio.h>

int main(){
    puts("hello world!");
    
    return 0;
}

The result is:

hello world!

The printf() function

The “int printf(const char *format, …)” function writes according to the format onto the output. The output format could be %d, %c, %s, etc. Take the example below:

#include <stdio.h>

int main(){
    printf("%d- %s", 1, "hello world!");
    
    return 0;
}

The result is:

1- hello world!

According to the format, the values are placed instead of %d and %s.

Was this helpful?
[0]
Scroll to Top
Scroll to Top