0

I am trying to read a txt file. I used a struct to declare all each element but I am running into an issue where I have commas in my txt file.

The file is as follows:

stan,10,10,100,100
paul,5,5,4,70
mikie,3,4,99,89
pat,1,1,99,55
greg,9,9,99,99
kay,5,5,99,50
mark,1,2,3,80

The file contains commas. The program cannot print out anything because of it. I know I can use space but I need the comma because all my other txt file include a comma.

This is the struct section.

struct studentRecord{
    string sname;
    int quiz1;
    int quiz2;
    int midExam;
    int finalExam;

};

This is the function:

double reward(struct studentRecord &record){

    if (record.finalExam >= 80){
        cout << record.sname << " Was given the award because he scored " << record.finalExam << " for his/her exam." << endl;
    }
    return 0;
}

And this is the main program:

int main(){

    ifstream  ifs("studentRecords.txt");
    string sname;
    int q1, q2, me, fe;
    struct studentRecord records[10];

    char comma;
    int i = 0;
    while (!ifs.eof()){
        ifs >> sname >> comma >> q1 >> comma >> q2 >> comma >> me >> comma >> fe;

        records[i].sname = sname;
        records[i].quiz1 = q1;
        records[i].quiz2 = q2;
        records[i].midExam = me;
        records[i].finalExam = fe;
        i++;
    }

    for (int j = 0; j < i; j++){
        double answer = reward(records[j]);
    }

}

I have seen examples of people declaring "comma" using char and then write it as sname >> comma >> q1 >> comma >> q2 >> comma >> me >> comma >> fe; I do not know if I am doing it right. Can you point out what I am missing or what is wrong? Much appreciated.

  • This would work if all your data was integer/real, for strings it won't do. – Yksisarvinen Feb 12 '21 at 14:52
  • `ifs >> sname` already reads till it encounters the first whitespace character, ie the whole line – 463035818_is_not_an_ai Feb 12 '21 at 14:53
  • 3
    Related: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – rustyx Feb 12 '21 at 14:54
  • 1
    [Here](https://godbolt.org/z/e56K1M)'s an alternative approach that might help. – Ted Lyngmo Feb 12 '21 at 15:03
  • Always search the internet before posting to StackOverflow. There are a plethora of results when searching for "C++ read file CSV" – Thomas Matthews Feb 12 '21 at 16:54

0 Answers0