Make a 3 by 3 array from a .txt file.

Hello, first post. I was just wondering how you create a 3 by 3 array from a ".txt" file. Just imagine this was inside the text file.

0 1 0
1 0 1
1 0 0

For my assignment, the text could change so I can't just create an array with the information as prior knowledge. I believe you would use something along the lines of ifstream or infile, I just don't completely understand these concepts yet. Thank you.
closed account (Dy7SLyTq)
read it into a int[3][3] where the first three corresponds to the current line and the second [3] corresponds to the current int
I know how to setup the array. I just dont know what to make every individual coordinate equal to the text file. I would assume you would need to use two for loops. This is what I do know.




int array[3][3];

for (int x = 0; x <= 2; x++)
{
for (int y = 0; y <= 2; y++)
{
array[x][y] = ***I don't know how to extract each coordinate from the file****;
}
}

closed account (Dy7SLyTq)
read it in with a string and use atoi. thats a really ugly way but i cant think of a better one
1
2
3
4
5
int array[3][3];

for ( int y=0; y<3; ++y )
    for ( int x=0; x<3; ++x )
        std::cin >> array[y][x] ;
closed account (Dy7SLyTq)
but he needs to get it from a file
Surprise. Works the same way.
@cire
aMo38 wrote:
I believe you would use something along the lines of ifstream or infile, I just don't completely understand these concepts yet

Anyways it's no big problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Beginning of .cpp file
#include <iostream>
#include <ifstream>

// Inside main()
std::ifstream filehandle("filename.txt");
int array[3][3];
bool Error = 0;
for(int y = 0; y < 3; ++y)
{
    for(int x = 0; x < 3; ++x)
    {
        if(Error = !(filehandle >> array[y][x]) )
            break;
    }
    if(Error)
        break;
}
if(Error)
{
    std::cout << "Error while Reading File." << std::endl;
}
Last edited on
Topic archived. No new replies allowed.