Flower
Flower

Reputation: 401

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

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

Upvotes: 4

Views: 30391

Answers (3)

Ulug Toprak
Ulug Toprak

Reputation: 1222

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
}

Upvotes: 2

yahiheb
yahiheb

Reputation: 147

Try this:

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::ifstream file("filename.txt"); // enter the name of your file here

    int firstLine;

    int secondLine;
    const int X = 3;
    const int Y = 1;
    const int Z = 1;
    int ***arr3D;

    std::string myArray[5];
    std::string myString;

    if (file.is_open())
    {
        // store the first line into an integer variable
        file >> firstLine;

        // store the second line into a 3d array index
        arr3D = new int**[X];
        for (int i = 0; i < X; i++)
        {
            arr3D[i] = new int*[Y];

            for (int j = 0; j < Y; j++)
            {
                arr3D[i][j] = new int[Z];

                for (int k = 0; k < Z; k++)
                {
                    file >> secondLine;
                    arr3D[i][j][k] = secondLine;
                }
            }
        }

        // store the final line into 5 elements of a string array
        int i = 0;
        while (file >> myString)
        {
            myArray[i] = myString;
            i++;
        }
    }

    file.close();


    std::cout << firstLine << std::endl;

    for (int i = 0; i < X; i++)
    {
        for (int j = 0; j < Y; j++)
        {
            for (int k = 0; k < Z; k++)
            {
                std::cout << arr3D[i][j][k] << std::endl;
            }
        }
    }

    for (int i = 0; i < 5; i++)
    {
        std::cout << myArray[i] << std::endl;
    }

    return 0;
}

Upvotes: 1

Polb
Polb

Reputation: 700

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;
}

Upvotes: 5

Related Questions