Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read text from .txt file into an array?

Tags:

c++

file

text

I want to open a text file and read it in its entirety while storing its contents into variables and arrays using c++. I have my example text file below. I would like to store the first line into an integer variable, the second line into a 3d array index and the final line into 5 elements of a string array.

I know how to open the file for reading but I haven't learned how to read certain words and store them as integer or string types.

3
2 3 3
4567 2939 2992 2222 0000
like image 476
Flower Avatar asked Oct 15 '25 15:10

Flower


2 Answers

Reading all the ints in a text file:

#include <fstream>

int main() {
    std::ifstream in;
    in.open("input_file.txt")
    // Fixed size array used to store the elements in the text file.
    // Change array type according to the type of the elements you want to read from the file
    int v[5];
    int element;

    if (in.is_open()) {
        int i = 0;
        while (in >> element) {
            v[i++] = element;
        }
    }

    in.close();

    return 0;
}
like image 131
Polb Avatar answered Oct 17 '25 05:10

Polb


Include the fstream:

#include <fstream>

And use ifstream:

std::ifstream input( "filename.txt" );

To be able to read line by line:

for( std::string line; std::getline( input, line ); )
{
    //do what you want for each line input here
}
like image 22
Ulug Toprak Avatar answered Oct 17 '25 06:10

Ulug Toprak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!