C++

How to Use scanf() in C++

C++ is a versatile programming language that includes several built-in functions. Among these functions, there is a widely used input function called scanf(). This article aims to provide a detailed overview of scanf() function in C++ by exploring its syntax, and behavior along with a simple example of using scanf() function in C++.

How to Use scanf() in C++

The scanf() is a widely used function in C that accepts input for a user, allowing programmers to enter an input of their choice instead of writing it in a program. It reads the data from the standard input (stdin) library. The scanf() function receives formatted data from standard input devices such as keyboards. The scanf() function is declared as follows.

scanf(format, ...)

The scanf() function accepts two parameters:

  • format: A string indicating the format of data to be read. This string may include conversion specifiers, which tell scanf() what kind of input to anticipate and how to read it.
  • (additional arguments): There are additional data that specify what data needs to be printed to the console. The data you specify here should be in sequence.

The scanf() function can be used to take any value whether it’s an integer, character, or any type. However, you must specify the data type using the format specifiers like %d, %s, %f, and more.

Example
The example of scanf() is given below:

#include <cstdio>
#include <iostream>
using namespace std;

int main() {
  int age;

  cout << "Please Enter Your Age: ";

  scanf("%d", &age);

  cout << "My Age is= " << age;
   
  return 0;
}

The above code accepts input from a user using the scanf() function, which is the age in this case. When you enter the desired number, it will be printed to the output using the cout function. Here we used the %d format to accept numbers.

Output

Conclusion

In C++, the scanf() function can be used to accept input from a user. The input can be in integers, characters, or floating numbers. Its syntax is pretty simple which only includes the format and additional arguments. For more details on how to use it in C++, follow the above-mentioned guidelines.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.