Search code examples
c++filefstreamtext-parsing

Read file with separator a space and a semicolon


I wrote this to parse a file with numbers, where the separator was just a space. My goal is to read every number of the file and store it in the corresponding index of the matrix A. So, the first number read, should go to A[0][0], second number to A[0][1] and so on.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main() {
    const int N = 5, M = 5;
    double A[N*M];
    string fname("test_problem.txt");
    ifstream file(fname.c_str());
    for (int r = 0; r < N; ++r) {
        for (int c = 0; c < M; ++c) {
            file >> *(A + N*c + r);
        }
    }

    for (int r = 0; r < N; ++r) {
        for (int c = 0; c < M; ++c) {
            cout << *(A + N*c + r) << " ";
        }
        cout << "\n";
    }
    cout << endl;

    return 0;
}

Now, I am trying to parse a file like this:

1 ;2 ;3 ;4 ;5
10 ;20 ;30 ;40 ;50
0.1 ;0.2 ;0.3 ;0.4 ;0.5
11 ;21 ;31 ;41 ;5
1 ;2 ;3 ;4 ;534

but it will print (thus read) garbage. What should I do?


EDIT

Here is my attempt in C, which also fails:

FILE* fp = fopen("test_problem.txt", "r");
double v = -1.0;
while (fscanf(fp, "%f ;", &v) == 1) {
    std::cout << v << std::endl;
}

-1 will always be printed.


Solution

  • You should remove semicolon before converting

    std::string temp;
    file >> temp;
    std::replace( temp.begin(), temp.end(), ';', ' ');
    *(A + N*c + r) =    std::stod( temp );