Insert data from text file into an array in C++

In this tutorial, we learned about how to insert data from a text file into an array in C++, with some easy examples.

let’s learn this with some easy steps.

  • Firstly we start from header file in which we used three header file(iostream,fstream,string) iostream is used for input output stream and fstream is used for both input and output operations and use to create files, string is used for Saving The Line Into The Array.
    #include <iostream>
    #include <fstream>
    #include <string>
  • then main function.Int tells the compiler that function will return an integer number.

How to insert data from a text file into an array in C++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
    string array[2]; 
    short loop=0; 
    string line; 
    ifstream myfile ("Codespeedy.txt"); 
    if (myfile.is_open()) 
    {
        while (! myfile.eof() ) 
        {
            getline (myfile,line); 
            array[loop] = line;
            cout << array[loop] << endl; 
            loop++;
        }
        myfile.close(); 
    }
    else cout << "can't open the file"; 
    system("PAUSE");
    return 0;
}

According to the above piece of code, we use a string array, it creates an array to hold names, the short loop is used for the loop for inputs, the string line will contain the data read from the file, we use if (myfile.is_open()) to check the file is open or not, while (! myfile.eof() ) is used for while the end of file is NOT reached
C++ provides a special function, eof(), that returns TRUE when there are no more data to read from an input file stream, and returns FALSE otherwise.
getline (myfile,line) is used to get one line from the file.

Note: always close the file after doing any operation on it.

when we apply this code the output will be like:

hello i am Raj Gaurav.
hello i am Raj Gaurav2.

also, read  how to count the number of lines in a text file with the help of c++ count the no of line in C++

Do let me know in the comments section if you have any doubts.

Leave a Reply

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