×

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream.

Syntax:

The syntax for the fscanf() function in the C++ programming language is as follows:

int fscanf( FILE* File_Name, const char* Format_Control, ... );

The fscanf() function scans the data from a file stream and saves it in the appropriate variables. It is declared in the header file, "<cstdio>."

Parameters for fscanf() function

File_Name: It is an input file stream from which data is read.

Format_Control: It is a null-terminated "char" (character) string pointer that describes how to read input data. It is made up of format specifiers beginning with "%."

The "Format_Control" string is made up of the following components:

1. Non-whitespace Characters: Except "%," each consumes one unique "char" (character) from the input file stream. If the following character in the stream does not match equality, the function may be able to fail.

2. Whitespace Character: All whitespace characters that follow one another are considered a single whitespace character. Furthermore, "\n," "\t," and " " are all considered to be the same.

3. Conversion Specifications:

It is formatted as follows:

  • The first "%" character indicates the beginning.
  • The character "*" is known as an assignment-suppressing character (optional).
  • If such a character is included, the result of the fscanf() function is not assigned to any accepting argument.
  • The maximum field width is specified by a positive integer value (optional). It defines the maximum number of characters that the fscanf() function may use while performing the conversion given by the conversion specifications.
  • The receiving argument's size is specified using a length modifier (optional).

Some Format Specifiers:

  1. “%” - It corresponds to the literal "%."
  2. “c” (Characters) - It can match a single character or several characters. If width is specified, then the width characters must match exactly.
  3. “s” (String of characters) - Consecutive non-whitespace characters are matched. If width is specified, it must match the exact width of the characters or until the first whitespace is encountered.
  4. “[character set]” (Scan set) - Any combination of the characters between the brackets. In some library implementations, a dash (-) that is not the initial character may cause non-portable behaviour.
  5. “[^ character set]” (Negated scan set) - Any combination of characters, none of which are indicated as characters between the brackets.
  6. “d” (Decimal integer) - Any combination of decimal numbers (0–9), optionally followed by a plus or minus sign (+ or –).
  7. “i” (Integers) - This corresponds to an integer.
  8. “u” (Integers) - It corresponds to an “unsigned” decimal integer.
  9. “o” (Octal integer) - Any number of unsigned octal numbers (0–7) followed by a sign (+ or -).
  10. “x” (Hexadecimal integer) - Any number of unsigned hexadecimal numbers (0-9, A-F), optionally followed by 0x, and all optionally followed by a sign (+ or -).
  11. “a,” “f,” “e,” “g” (Float point integers) - It corresponds to a float-point integer.
  12. “n” (Count) - There is no user input.
    The number of characters read from "File_Name" so far is saved in the location specified.
  13. “p” (Pointer) - It matches a character sequence defined by the implementation that defines a pointer.

As a result, the general syntax of the format specifier is as follows:

%[*][width][length]specifier
  • Another argument for receiving the data is that it appears in the order specified by the format specifier.

“fscanf()” Function Return Value

  • If successful, then the fscanf() method returns the number of successfully allocated receiving parameters.
  • It returns 0 if a matching failure happens before the initial receiving argument is assigned.
  • If the input fails before the initial receiving parameter is assigned, the error code EOF is returned.

Example

#include <cstdio>
int main (){
   	FILE *file_name;
   	char name[100];
int age;
    
   	file_name = fopen("example.txt","w");
    	fprintf(file_name, "%s %d", "Krishna", 18);
  	fclose(file_name);
file_name = fopen("example.txt","r");
   	fscanf(file_name, "%s %d", name, &age);
   	fclose(file_name);
printf("Good day, %s. You have %d years of age.\n", name, age);
    	return 0;
}

Output:

fscanf() Function in the C++

“fscanf()” Function Compatibility

Further specifiers and sub-specifiers may be supported by specific library implementations.

Those mentioned here are supported by the most recent C and C++ programming standards (both published in 2011), but their lengths are "hh," "ll," and so on, which were introduced by the C'99 version (only necessary for C++ system implementation since C++11) and could not be supported by libraries that attach to older standards.


Related Topics

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Different Ways to Compare Strings in C++

This section will go over the many methods for comparing strings in the C++ programming language. The string comparison checks if the first string is equal to another string. HELLO...

6 minutes read.