-1

I've spent the past two hours search this and other forums for pointers & guidance on how I can read a txt file, line by line, and store them in a 2D array that I can manipulate with other functions and then later save the array back to the text file; with little luck. Hopefully some bright spark can point me in the right direction.

Currently my text file contains data, separated by spaces, that looks like this:

Number1 Number2 Number3
Colour1 Colour2 Colour3
Letter1 Letter2 Letter3
...

The "getting and setting" of the 2D Array needs to be done in a separate function, and I think the array's need to be global because they will later be manipulated by other functions (i.e. add a new row, delete a row, etc.)

I know the start to the function will need to look something like this:

void getAndSetData()
{
   fstream file1;
   file1.open("1.txt", ios::in);
}

And will contain a nested for loop that will in turn, set the elements in the 2D array 1 by one. However, I'm really at a loss as how to go about this.

Thank you in-advance.

  • Hello please reference to this. http://stackoverflow.com/questions/30441732/store-txt-file-values-into-2d-array http://stackoverflow.com/questions/14539200/c-read-txt-contents-and-store-into-2d-array – Suad Halilović Jan 01 '17 at 23:28
  • study vector> and see the above comment to learn the types of questions stackoverflow is for. – doug Jan 01 '17 at 23:32
  • You're trying to solve several problems at once; tackle them one at a time. Can you read a single row of integers into `int[]` or `vector`? Can you read a string? Can you read a simple file of many lines? If you need help with *every* part of this problem, then you're attempting too difficult an exercise. – Beta Jan 01 '17 at 23:38
  • Thanks for the suggestion Beta. I have had success in reading the file, and even referencing an array e.g. Array1[0][0] returning: Number1, however I'm having trouble printing out the results in the same way that they're stored in the text file. – GuestUser140561 Jan 01 '17 at 23:41
  • Ah, so you're having trouble *printing* the array. What is the type of the array? Can you print the first line? Can you print a simple array like `int[3]`? – Beta Jan 01 '17 at 23:49

1 Answers1

0

Hello here is example code how I did it

ifstream in("test.txt");  // input file 
string my_array[3][200];

    void read_into_array()
    {
        if(in.is_open())
        {

            for(int i = 0; i < 200; ++i) // number of rows
            {
                for(int j = 0; j < 3; ++j) // number of columns
                {
                    in >> my_array[i][j];
                    cout<<my_array[i][j]<<"\t";
                }
                cout<<endl;
            }
        }
    }