0

I have a file with 2 lines, the first line in the pair has 4 numbers separated with a comma, and the second line in the pair has 3 numbers that also separated with a comma. I need to store these numbers in an array (not vector) so I can use them later.

Example:

Input file

0.994, 0.0, 0.0, -2.00158510638
17.0652165602, 1000, 1000

Output

arr[0] = 0.994
arr[1] = 0.0
arr[2] = 0.0
arr[3] = -2.00158510638
arr[4] = 17.0652165602
arr[5] = 1000
arr[6] = 1000

I tried to do the following:

std::string arr[7];
std::fstream inFile(file);
std::string part;
int counter = 0;
while(!inFile.eof())
{   
    getline(inFile, part, ' ');
    part.erase(std::remove(part.begin(), part.end(), ','), part.end());
    arr[counter] = part;
    counter++;
}
inFile.close();

But for some reason the last element in the array always gets zero. What might be the problem?

  • Also, a possible candidate: [SO: Reading through file using ifstream](https://stackoverflow.com/q/1619604/7478597). – Scheff's Cat Dec 29 '17 at 11:39
  • `while(!inFile.eof())` is [an automatic bug](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). So, this is already broken right at the starting gate. Then, this kind of an approach to parsing is very much error-prone, with many edge cases and error conditions that will be a pain to handle correctly. A much easier way to parse such input is to read each **entire** line, one line at a time, using `std::getline()`, then parse the read line and extract the individual values. You should start over from scratch, using this approach. – Sam Varshavchik Dec 29 '17 at 11:45

0 Answers0