I have data in a txt file named Test2.txt that looks like this.

1a,1b,1c,1d,1e
2a,2b,2c,2d,2e
3a,3b,3c,3d,3e
4a,4b,4c,4d,4e
5a,5b,5c,5d,5e

I want to put this data into a 2D array so that dataArray[0][0] will hold 1a, dataArray[0][1] will hold 1b, dataArray[1][0] will hold 2a, etc.

However, the problem is that I need to parce my data by a return stroke and a comma. When I do the getline functions, I can parce it by returns without trouble, but parcing by a comma doesn't work like I want it to. In the end, I end up assigning an entire comma delimited line to one array index. Here is my code. (I hope I put this in right, it's my first time posting).

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    const int ROW = 5;
    const int COL = 7;
    int i,j;
    string fileLine;
    string fileData;
    string dataArray[ROW][COL];

                ifstream inFile;                        
    inFile.open("Test2.txt");                   

    if(inFile)
    {
        while(!inFile.eof())    
        {
            getline(inFile,fileLine);
            stringstream iss;
            iss << fileLine;
            for(i=1;i<ROW;i++)
            {
                for(j=1;j<COL;j++)
                {
                    while(getline(iss,fileData,','))
                    {
                        dataArray[i][j] = fileData;
                        cout << dataArray[i][j] << endl;
                    }
                }
            }
            iss.clear();
        }
    }
    else
    {
        cout << "Error in opening file" << endl;
    }

    inFile.close(); 

    system("pause");

    return 0;
}

Now the output for this looks like it works because it lists 1a through 7e. However, these weren't assigned to the correct array indices.

I'd appreciate any tips anyone has, even if it means taking another approach in reaching my goal.

Recommended Answers

All 2 Replies

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
   ifstream file("Test2.txt");              
   if ( file )
   {
      const int ROW = 5, COL = 7;
      string array[ROW][COL];
      for ( int i = 0; i < ROW; i++ )
      {
         string line;
         if ( getline(file, line) )
         {
            stringstream iss(line);
            for ( int j = 0; j < COL; j++ )
            {
               if ( getline(iss, array[i][j], ',') )
               {
                  cout << "array[" << i << "][" << j << "] = " 
                       << array[i][j] << '\n';
               }
            }
         }
      }
   }
   else
   {
      cout << "Error in opening file" << endl;
   }
   return 0;
}

Thanks Dave, that worked well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.