scanf() in C - Source Code Example

In this source code example, we will see how to use the scanf() function in C programming with an example.

Function Overview

The scanf() function, found in the C standard library's <stdio.h>, is a crucial function for formatted input. It enables users to read input from the standard input (typically the keyboard) and store them into variables. Much like printf(), it utilizes format specifiers to cater to various data types, ensuring that the correct type and amount of input is read.

Source Code Example

#include <stdio.h>

int main() {
    // Basic integer input
    int age;
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("You entered age: %d\n", age);

    // Floating point input
    double salary;
    printf("Enter your salary: ");
    scanf("%lf", &salary);
    printf("You entered salary: %.2lf\n", salary);

    // Character input
    char initial;
    printf("Enter your initial: ");
    scanf(" %c", &initial);  // Note the space before %c to consume any preceding whitespace
    printf("You entered initial: %c\n", initial);

    // String input
    char name[50];
    printf("Enter your name: ");
    scanf("%s", name);  // Strings don't need & in front of the variable name
    printf("You entered name: %s\n", name);

    return 0;
}

Output

Enter your age: 25
You entered age: 25
Enter your salary: 5000.50
You entered salary: 5000.50
Enter your initial: A
You entered initial: A
Enter your name: Alice
You entered name: Alice

Explanation

In the given source code example:

1. We use scanf() with the %d format specifier to read an integer value for the age variable.

2. For floating-point numbers, the %lf format specifier is employed to read the value of salary.

3. The character input is read using the %c format specifier. A noteworthy point here is the space before %c to ensure any prior whitespace characters are consumed.

4. To read strings, the %s format specifier is used. When working with strings, it's essential to remember not to use the & before the string variable name.

The scanf() function, with its format specifiers, provides an efficient way to gather and process user input, making it a foundational tool in C programming.


Comments