Reading from a file and storing into an array

Hi, everyone I could really use your help. I have this text file
1
2
3
1x+1y+1z=5
2x+3y+5z=8
4x+0y+5z=2

And I want to store into a file. Once I stored into a file I want the output to be this:
1
2
3
4
5
6
1x+1y+1z=5
a=1 b=1 c=1 d=5
2x+3y+5z=8
a=2 b=3 c=5 d=8
4x+0y+5z=2
a=4 b=0 c=5 d=2


This is the code I have, but for some reason it is not working. I am new to c++, so I am probably not using the correct syntax.

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
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    ifstream file("matrix.txt");

    if (!file)
    {
        cout << "Could not open input file\n";
        return 1;
    }


    for (string line[10]; file.getline(line, 10); )
    {
        cout << line << '\n';
        istringstream ss(line);

        double a, b, c, d;
        char x, y, z, eq;

        if (ss >> a >> x >> b >> y >> c >> z >> eq >> d)
        {
            if (x == 'x' && y == 'y' && z == 'z' && eq == '=')
            {
                cout << "a = " << a
                     << "  b = " << b
                     << "  c = " << c
                     << "  d = " << d << '\n';
            }
            else
            {
                cout << "parse error 2\n";
            }
        }
        else
        {
            cout << "parse error 1\n";
        }

    }

}
Last edited on
“It's not working” == it will not compile. Crank up your compiler warnings to max and look at the top one — this will give you the most important clue. GCC tells me:

a.cpp: In function 'int main()':
a.cpp:19:48: error: no matching function for call to 'std::basic_ifstream<char>::getline(std::__cxx11::string [10], int)'
     for (string line[10]; file.getline(line, 10); )
                                                ^
 
It is saying that it cannot find a “getline()” function that takes an array of ten strings and an integer.

Fix your program thusly:

18
19
    string line;
    while (getline( file, line ))

Otherwise, your program looks great. Nice job!

Hope this helps.
Registered users can post here. Sign in or register to post.