### 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
 ``12345`` ``````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:

 ``1234567891011121314151617181920212223`` `````` // Beginning of .cpp file #include #include // 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.