Reading data from a file, basic.

I want to read columns of data from a . dat file and store them in an array.

my data file looks like this:

X-Mesh
1 0.000000000000000000E+00 0.830078124999999978E-03 1.00000000000000000
2 0.830078124999999978E-03 0.830078124999999978E-03 1.00000000000000000
3 0.166015624999999996E-02 0.830078124999999978E-03 1.00000000000000000

.....and so on.

Each column contains distinct information, and I wanna read them and store in
3 distinct arrays in my c++ program. What function or algorithms are required?

Now I am thinking of using "getline(fin, str)" to store each line in a string called str,
then break the string into 3 numbers, but I have no idea how to break string to
numbers that consist of str. (fin is ifstream object.)
(No round off and truncation is allowed. what is a proper data type?)

It would be great if you can give a few lines of sample code.
I appreciate it.
Last edited on
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
#include <fstream>
#include <string>
#include <vector>


typedef std::vector < std::string > Strings;

inline Strings split(const std::string &s, const char *by = " ")
{
    Strings res;
    res.reserve(2);
    const unsigned int SIZE = s.size();
    unsigned int i(0);
    unsigned int j(0);
    for (i = 0; i <= SIZE; i = j + 1)
    {
        for (j = i; j < SIZE && strchr(by, s[j]) == NULL; j++)
        {;}
        res.push_back(s.substr(i, j-i));
    }
    return res;
}

std::vector <Strings> getFileContent(const char* file)
{
    std::ifstream fs(file);
    std::vector <Strings> retVal;
    std::string line;
    while(std::getline(fs, line)
    {
        if(line == "X-Mesh")
        {
              continue;
        }
        retVal.push_back(split(line));
    }
    return retVal;
}

Small note: an STL vector may not be the best container to read in a data file. If the data file is large, the vector will have to resize each time that it reaches it's reserved size. Remember that a vector is stored in contiguous memory, so each internal resize involves copying the entire contents of the container.
Last edited on
thanks for comment,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

typedef std::list <Strings> ContainerArrays;

ContainerArrays getFileContent(const char* file)
{
    std::ifstream fs(file);
    ContainerArrays retVal;
    std::string line;
    while(std::getline(fs, line)
    {
        if(line == "X-Mesh")
        {
              continue;
        }
        retVal.push_back(split(line));
    }
    return retVal;
}
Has anyone tried reading the numeric data like this:
1
2
3
4
5
6
7
8
#include <fstream>
//...
ifstream f( "datafile" );
double n;
while( f >> n )
{
    cout << n << endl;
}

I think it will work but you'll likely lose some precision.
Topic archived. No new replies allowed.