how to read file into array

the data is
Last edited on
The primary problem is that not everything is comma separated in the file. For instance:

"T1",267.128,343.000
"T2",267.128,225.000

The first string you read is: "T1", the second is 267.128, and the third is 343.000\n"T2"

Here's a more flexible approach:

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
#include<iostream>
#include <fstream>
#include <string>

using namespace std ;

string testpt[20][3] ;

int main()
{
    const char separator[3] = { ',', ',', '\n' } ;

    ifstream infile("test.dat");

    unsigned recordsRead = 0 ;

    while ( infile && recordsRead < 20 )
    {
        for ( unsigned i=0; i<3 ; ++i )
            getline( infile, testpt[recordsRead][i], separator[i] ) ;
 
        if ( infile )
            ++recordsRead ;
    }

    cout << "Records read: " << recordsRead << '\n' ;

    for ( unsigned i=0; i < recordsRead ; ++i )
    {
        for ( unsigned j=0; j<3 ; ++j )
            cout << testpt[i][j] << ' ' ;
        cout << '\n' ;
    }       
}


[Edit: Btw, please use code tags in the future, it makes your posts much more readable. Look for the <> button.]
Last edited on
Topic archived. No new replies allowed.