How to Read Integers From a File in C++?

How to Read Integers From a File in C++?

Do you want to learn how to read integers from a file in C++? 🤔 Then keep reading this article 👇, its just for you.

Data is stored in memory while a program runs, but it is lost when it terminates, or the computer shuts down. Data must be written into a file in order to be permanently stored. You can store data in files in C++. 

In this article, we’ll discuss various C++ techniques used to read integer data from files. In addition to that, you’ll also learn how to read and write data to files in C++. The iostream, fstream are the two standard C++ libraries that are used to read and write files.

In the examples that follow, we’ll assume that file.txt is a text file with numerous lines of space-separated integer numbers. It should be noted that each example program verifies that the filename corresponds to the real file stream and emits the appropriate error message in the case of an error.

 

 

What Are The Different File Handling Operations in C++?

In C++, different data types are being used from the fstream library for file handling. To create files and write to existing files, use ofstream. When reading from files, you can use ifstream and streamIt can create files, write to files, and read from files. It can also perform the functions of both ofstream and ifstream.

 

 

How to Open a File in C++?

We must inform the computer why we want to open our file. Examples include writing to the file, reading from the file, etc. These are the several ways that a file can be opened. There are certain modes by which you can open a file. Following are the modes given below:

  1. Ios::app mode
  2. ios::ate mode
  3. Ios::in mode
  4. Ios::out mode
  5. Ios::trunc mode

 

Ios::app Mode

This mode enables appending to a text file. Adding text at the end is known as appending.

 

Ios::ate Mode

This read/write control is moved to the end of the file as the file is opened for output.

 

Ios::in Mode

This mode enables the reading of a text file.

 

Ios::out Mode

This mode enables text editing in a file.

 

Ios::trunc Mode

This mode truncates the content if a file already exists before opening it.

 

Code

#include <iostream>

#include <fstream>




using namespace std;




int main(){

  ofstream file;

  file.open ("file.txt");

  return 0;

}

 

To write in the file file.txt, we have opened it. You must first create the file.txt file in your working directory.

 

 

How to Read And Write in a File in C++?

First, you have to create a file, and then you have to open that file using the example code above. The file may be opened for both reading and writing. Let’s see an example below:

 

Code

#include <iostream>

#include <fstream>




using namespace std;




int main(){

  fstream file;

  file.open ("file.txt", ios::out | ios::in );

  return 0;

}

 

In the above example, we have opened a file named file.txt in  ios::out mode for writing data into the file and ios:: in mode to read the data in the file.

 

 

How to Close a File in C++?

All memory allocated is automatically closed and released by C++. However, a programmer must always save all opened files. Let’s look at how to wrap everything up.

 

Code

#include <iostream>

#include <fstream>




using namespace std;




int main(){

  ofstream file;

  file.open ("file.txt");

  file.close();

  return 0;

}

 

After we are done with any sort of work with the file, we can close it using the close function.

 

 

How to Read Integers From a File in C++?

Following are the methods for how to read integers from a file in C++:

  1. Using Operator 
  2. Using Operator and push_back Method 
  3. Using ifstream Method 

 

 

Method 1: Using Operator

This function stores each integer in the number variable and iterates the operation until the EOF (end of the file) is reached. The body of the loop may then report each integer to the console. Let’s see an example:

 

Code

#include <iostream>

#include <fstream>




using std::cout; using std::cerr;

using std::endl; using std::string;

using std::ifstream;




int main()

{

    string filename("data.txt");

    int number;




    ifstream file(filename);

    if (!file.is_open()) {

         cerr << "The file does not exist - '"

             << filename << "'" << endl;

        return EXIT_FAILURE;

    }




    while (file >> number) {

        cout << number << ": ";

    }

    cout << endl;

   file.close();

   return EXIT_SUCCESS;


}

 

Output

126: 1328: 1099: 339:

 

In the above example, we are adding a semicolon to the next integer in the file. 

 

 

Method 2: Using Operator And Push_back Method

Another example is to get every integer from the file, store it in the number variable as in the preceding example, and then push each one into the int vector in turn. You’ll see that this example has an additional for loop to mimic a more practical system where manipulating the stored vector numbers’ members is necessary. Let’s see an example:

 

Code

#include <iostream>

#include <fstream>

#include <vector>




using std::cout; using std::cerr;

using std::endl; using std::string;

using std::ifstream; using std::vector;




int main()

{

    string file_name("example.txt");

    vector<int> numbers;

    int num;




    ifstream in_file(file_name);

    if (!in_file.is_open()) {

        cerr << "This file does not exist - '"

             << file_name << "'" << endl;

        return EXIT_FAILURE;

    }




    while (in_file >> num) {

        numbers.push_back(numbers);

    }




    for (const auto &i : num) {

        cout << i << ": ";

    }

    cout << endl;

    in_file.close();




    return EXIT_SUCCESS;

}

 

Output

126: 1328: 1099: 339:

 

In the above example, we are using a while loop with a pushback method to insert a semicolon after every integer in the Example.txt file and then print it.

 

 

Method 3: Using The Ifstream Method

The eof() function might be used as a while loop condition to solve the same issue. Sadly, that could necessitate a further iteration. Due to the fact that eof() only returns true if the eofbit is set, it is possible for an uninitialized object to change throughout an iteration.  Let’s see an example:

 

Code

#include <iostream>

#include <fstream>

#include <vector>




using std::cout; using std::cerr;

using std::endl; using std::string;

using std::ifstream; using std::vector;




int main()

{

    string file_name("example.txt");

    vector<int> num;




    ifstream in_file(file_name);

    if (!in_file.is_open()) {

        cerr << "This file doesn't exist - '"

             << file_name << "'" << endl;

        return EXIT_FAILURE;

    }




    while (!in_file.eof()) {

        int tmp;

        in_file >> tmp;

        num.push_back(tmp);

    }




    for (const auto &i : num) {

        cout << i << ": ";

    }

    cout << endl;

    in_file.close();



    return EXIT_SUCCESS;

}

 

Output

126: 1328: 1099: 339:

 

In the above example, we are using the if stream to read the integers from the file example.  text

 

 

Conclusion

To summarize the article, we have discussed how to open a file in C++ in different modes, read from and write to a file, and how to close a file in C++. Furthermore, in this article, we have discussed how to read integers from a file in C++. We have also talked about the three different techniques that help you read an integer from a file in C++

The first is to use a while loop with an operator, the second is to use a while loop with an operator and a pushback method, and the third is to use the ifstream method. 

The best way to read an integer from a file in C++ is to use the ifstream method, as we don’t have to iterate again and again, just like in the case of a while loop. 

Let’s have a quick recap of the topics discussed in this article.

  1. How do open, close, and read and write data From a File in C++?
  2. How to read integers from a file in C++?
  3. Using operator. 
  4. Using the operator and push_back method. 
  5. Using the ifstream method.

If you’ve found this article helpful, don’t forget to share and comment below. 👇: Which solutions have helped you solve the problem?

 

 

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts
Total
0
Share