scanf() function in C++

In this guide, you will learn what is scanf() function is in C++ programming and how to use it with an example.

1. scanf() Function Overview

The scanf() function is a part of the <cstdio> library in C++. It is used to read formatted input from the standard input. The function interprets the format string and reads input from the standard input based on the specified format, then assigns the input to subsequent arguments.

Signature:

int scanf(const char* format, ...);

Parameters:

- format: A string that contains text and format specifiers, which define the expected data types for the subsequent arguments.

- ...: Variable number of arguments that will receive the values read from standard input.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    int age;
    char name[50];

    // Read formatted input from the standard input
    printf("Enter your name: ");
    scanf("%s", name);

    printf("Enter your age: ");
    scanf("%d", &age);

    printf("Name: %s\nAge: %d\n", name, age);

    return 0;
}

Output:

Enter your name: JohnDoe
Enter your age: 25
Name: JohnDoe
Age: 25

3. Explanation

1. We define an integer age and a character array name to store the input values.

2. The printf() function is used to display a message asking the user to input their name.

3. The scanf() function is then used to read the user's name using the %s format specifier.

4. Similarly, the user's age is read using the %d format specifier.

5. Finally, the input values are printed using the printf() function.

Note: When using scanf() for reading strings, it's crucial to ensure that the input does not exceed the size of the character array. Also, the format specifiers in scanf() should match the type of the provided arguments; otherwise, undefined behavior can occur.


Comments