I am trying to read matrix data from file into a float vector

the file has data like

X = {1.0, 2.0, 3.0...........}
Y = {3.4, 3.1, 3.4...........}

I can read into vector strings. But I want to store the matrix names in a string vector and the matrix in a float vector

here is the code

using namespace std;
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <string>

int main(void) {
vector<string>o;
vector<float> a;

FILE *fw;

fw = fopen("input1.txt", "r");

char str[100];
float f;
while (!feof(fw)) {
string newstr="";
while (1) {
int c=fgetc(fw);
// if (c==',' || c=='|'||feof(stdin)) break;
newstr.push_back((char)c);
if(c=='{')
{
while(c!='}'){
int c=fgetc(fw);
// while (fgets(str,sizeof(str),fw)!=NULL){
// fscanf (fw, " %f", &f);
// printf("%f\n",f);
newstr.push_back((char)c);
}

}
}
}
o.push_back(newstr);
a.push_back(newstr);
// }

for (unsigned int i=0;i<o.size(); i++)
printf(" String %d is %s\n", i, o[i].c_str());

for (unsigned int j=0;j<a.size(); j++)
printf(" String %f is %s\n", j, a[j].c_str());

return 0;
}

Here is one way to do it -- first read the entire line into a std::string object then parse it

int _tmain(int argc, _TCHAR* argv[])
{
    vector<string> sList;
    vector<float> fList;
    string name;
    float f;
    string line = "X = {1.0, 2.0, 3.0}";

    // extract the name which 
    size_t pos = line.find(' ');
    name = line.substr(0,pos);
    line = line.substr(pos+1);
    pos = line.find('{');
    line = line.substr(pos+1);
    while( (pos = line.find(',')) != string::npos)
    {
        string n = line.substr(0,pos);
        f = (float)atof(n.c_str());
        fList.push_back(f);
        line = line.substr(pos+1);
    }
    // now do the last float in the line
    f = (float)atof(line.c_str());
    fList.push_back(f);
	return 0;
}
This article has been dead for over six months. Start a new discussion instead.