0

I have .txt file with text like this inside (this is just a fragment):

...
[332, 605]-[332, 592], srednica: 13
[324, 593]-[332, 605], srednica: 14.4222
[323, 594]-[332, 605], srednica: 14.2127
[323, 594]-[331, 606], srednica: 14.4222
[324, 593]-[324, 607], srednica: 14
[323, 594]-[323, 607], srednica: 13
[319, 596]-[319, 607], srednica: 11
[320, 595]-[320, 607], srednica: 12
... 

What i need to to is get a first 4 numbers from each line and store them into integers.

I have tried smth like this:

ifstream file("punkty_srednice.txt");
string line;
int ax, ay, bx, by;
while(getline(file, line)) {
    stringstream s(line);
    string tmp;
    s >> tmp >> ax >> tmp >> ay >> tmp >>  bx >> tmp >> by >> tmp;
    cout << ax  << " " << ay <<  " " << bx << " " << by << endl;
}

Output (just a part of it):

...
506 506 -858993460 -858993460
503 503 -858993460 -858993460
495 503 -858993460 -858993460
497 503 -858993460 -858993460
500 497 -858993460 -858993460
492 503 -858993460 -858993460
...

As u an see there are some strange numbers like -858993460

I did other try by deleting tmp and going straight like this:

s >> ax >> ay >>  bx >> by;

but then output contains only trash numbers like -858993460

How i can deal with it?

countryroadscat
  • 1,660
  • 4
  • 26
  • 49

1 Answers1

1

You can use std::getline with the ',' as separator to get the first parts, with the numbers. Then replace all non-digit characters with space (see e.g. std::transform). Then put the resulting string in an std::istringstream and read four numbers from it.


Some tips on what's wrong with your code, it mostly boils down to that when used with strings, the input operator >> reads space delimited strings.

So for the line

[332, 605]-[332, 592], srednica: 13

your input will be

  1. into tmp it will put "[332,"
  2. into ax it will put the 605
  3. into tmp it will put "]-[332,"
  4. into ay it will put 592
  5. into tmp it will put "],"
  6. into bx it will try to read the string "srednica" which is not a valid number, and the input will fail and set the fail flag on the input stream, making all the following inputs invalid

How to replace any non-digit character in a string to a space using std::transform:

std::string s = "[332, 605]-[332, 592]";
std::cout << "Before: \"" << s << "\"\n";

std::transform(std::begin(s), std::end(s), std::begin(s),
    [](const char& ch) -> char
    {
        return (std::isdigit(ch) ? ch : ' ');
    });

std::cout << "After : \"" << s << "\"\n";

The above code prints

Before: "[332, 605]-[332, 592]"
After : " 332  605   332  592 "
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621