How would I read a file into an multidimensional array or three seperate arrays based on a sequence of delimiters?

New to c++ and programming, and I am having trouble figuring this out.

Pseudo idea; Assuming I can define the delimiters

 
 ',' ',' '\n' 


then read file line by line while adding each element to each array.

1
2
3
4
5
#define ARRAY_SIZE 1000 

string someString[ARRAY_SIZE];
double someDoubble[ARRAY_SIZE];
double someDoubble[ARRAY_SIZE]; 


Then the text file that I am reading is

somestring, someDouble, someDouble\n

Or in other words the delimiters are comma, comma, newline char.
Without redefining delimiters, you would have to use getline() to read that first string up until the comma:

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

int main()
{
    std::vector<std::string> someString;
    std::vector<double> someDouble;
    std::vector<double> someOtherDouble;

    std::ifstream file("test.txt");
    std::string s;
    double d1, d2;
    char ch;
    while(    file >> std::ws // skip leading whitespace
           && getline(file, s, ',') // read until comma into string s
           && file >> d1 >> ch >> d2
           && ch == ',' ) // make sure it was a comma
    {
        someString.push_back(s);
        someDouble.push_back(d1);
        someOtherDouble.push_back(d2);
        std::cout << "saving " << s << " : " << d1 << " : " << d2 << '\n';
    }
}


or you could make the parsing a bit easier by defining comma as whitespace.. you may not want to do that if you're "new to C++ and programming", but do keep in mind that it's available

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>
#include <vector>
#include <locale>

struct comma_space : std::ctype<char> {
    static const mask* make_table() {
        static std::vector<mask> v(classic_table(), classic_table() + table_size);
        v[','] |=  space;  // comma will be classified as whitespace
        return &v[0];
    }
    comma_space(std::size_t refs = 0) : ctype(make_table(), false, refs) {}
};


int main()
{
    std::vector<std::string> someString;
    std::vector<double> someDouble;
    std::vector<double> someOtherDouble;

    std::ifstream file("test.txt");
    file.imbue(std::locale(file.getloc(), new comma_space));
    std::string s;
    double d1, d2;
    while( file >> s >> d1 >> d2 )
    {
        someString.push_back(s);
        someDouble.push_back(d1);
        someOtherDouble.push_back(d2);
        std::cout << "saving " << s << " : " << d1 << " : " << d2 << '\n';
    }
}
Topic archived. No new replies allowed.