Tokenizing a string array.
Oct 2, 2017 at 4:33am UTC
Hello, everyone. I need some help parsing a string array. I have a file that has equations stored in them. I only want to store the numbers in my array. The file cotains:
1 2 3
1x+1y+1z=5
2x+3y+5z=8
4x+0y+5z=2
My code is:
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
int main(){
fstream file;
file.open("matrix.txt" , ios::in);
string *arr = new string[3];
// copy integers into array and display
for (int i = 0; i < 3; i++){
getline(file, arr[i]);
cout << arr[i] << endl;
}
delete [] arr;
}
How can I store
1 1 1 5
2 3 5 8
4 0 5 2
in my array?
Last edited on Oct 2, 2017 at 4:38am UTC
Oct 2, 2017 at 6:07am UTC
You could use a
stringstream
to parse the contents of the string.
A line such as this:
breaks down as follows:
number 1
character x
number +1
character y
number +1
character z
character =
number +5
Here's a very generalised code which tries to read data of that kind.
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
#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; getline(file, line); )
{
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" ;
}
}
}
I was just thinking in terms of an unknown number of lines in the file.
However, mathematically it looks like three equations in three unknowns, and would suit a 4 x 3 array, which I haven't done here.
Topic archived. No new replies allowed.