2d array - nested loop with getline()

Hi,

I have a conceptual problem. After some research and help I managed to read data from a text file and input it into 2d array. However, because of the "multi delimiter" issue, I had to create a nested loop to gather the data.

Assuming that we have the following .txt file:

1;10
2;20
3;30
4;40
5;50
6;60

The delimitors being ';' and '\n'.

Below the code...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <curses.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <math.h>
using namespace std;  

int main () {
    int i=0,j=0, counter=0;
    string line;
    string array[10000][2];
    int array_int[10000][2];

//Rename .csv file to .txt file
rename("eurusd.csv","rates.txt");

//Opening file for I/O
    fstream ratesfile("rates.txt");   
    if (ratesfile.is_open()) printf("File Open\n"); else printf("File not open\n");   
    cin.get();
    
   
//Loading .txt file data into array 
string token;
stringstream iss;

           
	while(getline(ratesfile, line)) {
          iss << line;

           while(getline(iss, token, ';')) {                                                     
                   array[i][j] = token;
                   cout << array[i][j] << endl;
				   counter++;
				   
//NOW here all values are in fact loaded in array[0][0], I want them to be loaded in array[0][0], then array[0][1], etc...
			    }
             iss.clear();
            }

     ratesfile.close();   
  
     cout << "Loaded array[i][j]" << array[0][0] << endl;
	 cin.get(); //This shows that the loading was unsucessfull

  
   //Checking if the string arrays have been filled correctly   
     for(int i = 0; i < 6; ++i) {cout << "Loaded numbers:" << array[i][0] << endl;} 
	 cin.get(); //This shows that the loading was unsucessfull

	return 0;
}


I get where the problem is, however I need an intelligent manner the fill the "array[i][j]" which happen to be in the 2nd "while" of a nested loop...
It looks like you need to actually change the values of i and j.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	i = 0; // set i to first line
	while(getline(ratesfile, line)) {
          iss << line;
	  j = 0; // set j to first item
           while(getline(iss, token, ';')) {                                                     
                   array[i][j] = token;
                   cout << array[i][j] << endl;
				   counter++;
				++j // move on to next item				   
			    }
             iss.clear();
		++i; // move on to next line
            }


That might work. Its very sensitive to correct input data though which is never a good thing.
Works perfect thx for your help.
Topic archived. No new replies allowed.