0

I have following struct definition:

struct Sportsman
{
    string name;
    double points[7];
    double avr_point; 
};

I want to read following file content to array of structs:

Petrov 4,9 5,3 5,0 5,0 4,9 5,3 5,5
Ivanov 6,0 5,9 5,9 5,7 5,7 5,8 5,9

This is how I tried:

ifstream fin("sportsman.txt");
string line;
int i = 0;
while (getline(fin, line))
{
    sscanf(line.c_str(), "%s %lf %lf %lf %lf %lf %lf %lf", &sm[i].name, &sm[i].points[0], &sm[i].points[1], &sm[i].points[2], &sm[i].points[3],
                          &sm[i].points[4], &sm[i].points[5], &sm[i].points[6], &sm[i].points[7]);
    i++;
}

But struct field "name" doesn't fill properly. It looks like first four characters are ignored and I get only part "ov" for "Petrov" and "Ivanov", while points are fine.

So, how should I use sscanf and %s to read names in correct way?

st_dec
  • 142
  • 1
  • 11
  • 1
    Better use `operator >>`, it will be something like `fin >> sm[i].name`, the rest you can read using loops – oybek May 08 '19 at 13:01
  • 2
    You should never use `%s` in general. In this case it's not just a buffer overflow waiting to happen, it's also a type error: `%s` takes a `char *`, not a `std::string *`. – melpomene May 08 '19 at 13:03

0 Answers0