×

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

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.

Dynamic Constructor in C++

Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory...

2 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

Print Table Using While Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.