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; 
    else cout << "can't open the file"; 
    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.

3 responses to “Insert data from text file into an array in C++”

  1. mimi says:

    i dont know why but when i’m passing array n inputfile to readFile fx,it didnt work i’m using while loop (!inputfilename.eof())

  2. Owen John Evans says:

    Where is the data file located? The same folder as the source code?

  3. Danaa says:

    it works when I separately output the array elements within the function, however, it gives a runtime error in these two cases:
    1) whenever I try to output the contents of my string array with a loop within the function
    2) whenever I return the string to my main function
    how do I fix this?

Leave a Reply

Your email address will not be published.