c++ - Read file with separator a space and a semicolon -
i wrote parse file numbers, separator space. goal read every number of file , store in corresponding index of matrix a. so, first number read, should go a[0][0], second number a[0][1] , 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()); (int r = 0; r < n; ++r) { (int c = 0; c < m; ++c) { file >> *(a + n*c + r); } } (int r = 0; r < n; ++r) { (int c = 0; c < m; ++c) { cout << *(a + n*c + r) << " "; } cout << "\n"; } cout << endl; return 0; }
now, trying parse file 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 print (thus read) garbage. should do?
edit
here attempt in c, fails:
file* fp = fopen("test_problem.txt", "r"); double v = -1.0; while (fscanf(fp, "%f ;", &v) == 1) { std::cout << v << std::endl; }
-1 printed.
you should remove semicolon before converting
std::string temp; file >> temp; std::replace( temp.begin(), temp.end(), ';', ' '); *(a + n*c + r) = std::stod( temp );
Comments
Post a Comment