Using Scanf in C Program


In our previous video tutorial you learnt about Integers, Float and Character data types and their format specifier. In today’s video lets see an example of using all 3 data types along with strings.

You’ll also learn to get user input from console using scanf function/method present in stdio.h header file.

Example: int, float, char

 
#include< stdio.h >

int main()
{
    int a;
    float b;
    char ltr;

    printf("Enter 2 numbers and a single character\n");
    scanf("%d %f %c", &a, &b, <r);

    printf("\nYou entered %d, %f and %c", a, b, ltr);

    return 0;
}

Output:
Enter 2 numbers and a single character
1 2 i

You entered 1, 2.000000 and i

Example for string type

 
#include < stdio.h >

int main()
{
    char c[10];

    printf("Enter a company name\n");
    scanf("%s", c);

    printf("\nYou entered %s", c);

    return 0;
}

Output:
Enter a company name
Microsoft
You entered Microsoft

Using Scanf() To Read Int, Float, Char and String Data Type: C Programming


[youtube https://www.youtube.com/watch?v=myqWGZePUgg]

YouTube Link: https://www.youtube.com/watch?v=myqWGZePUgg [Watch the Video In Full Screen.]


Keyword for Integer is int and its format specifier is %d.
Keyword for Float is float and its format specifier is %f.
Keyword for Character is char and its format specifier is %c.

Note 1: If you input decimal value for a integer variable, it only stores integer part of the value and discards the decimal value.

Note 2: printf and scanf are kind of opposite. Because printf converts all the numbers, characters etc and displays everything in text format on to the console. While, scanf takes all the text entered by the user in the console and converts them into respective data type based on the format specifier present in scanf statement.

Leave a Reply

Your email address will not be published. Required fields are marked *