1

I have a file with 198 (however it could at any point be between 0-200) lines. Each line of my file looks like this:

Urdnot Wrex,2.75,198846.13
Urdnot Bakara,3,189484.84
Hannah Shepard,1.75,188145.14
David Anderson,2.25,182169.46
Kasumi Goto,2.75,176795.83

This is my code, however, it does not want to work.

int index = 0; // The index of the file.

while(index <= 200) {
    in.ignore(256, ',');
    in >> employeeName;
    in.ignore(256, ',');
    in >> employeeScore;
    in.ignore(256, '\n');
    in >> employeeSalary;

    cout << index << ": " << employeeName << ", " << employeeScore << ", " << employeeSalary << endl;
    index++;
}

However, with a file with 198 lines it only reads 3 with the output being:

0: 2.75,198846.13, 3, 0
1: 2.75,198846.13, 3, 0
2: 2.75,198846.13, 3

If anyone has any ideas on how to make it work, that would be much appreciated.

Levi Pawlak
  • 11
  • 1
  • 2

1 Answers1

1

Like this:

#include <fstream>

std::ifstream infile("thefile.txt");
if (infile.is_open()) {
    float number;
    std::string str;
    char c;
    while (infile >> str >> c >> number && c == ',')
        cout << number << " " << str << "\n";
}
infile.close();
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • What if you have a case like a (name, 1)? ( it won't work since the name, is considered as a whole world, and not name + delimiter ',' ). A nice solution is to use std::getline with stringstream for those kinds of parsing stuff. – pureofpure Jan 11 '21 at 09:19