Home > Software engineering >  Reading file from .csv in c
Reading file from .csv in c

Time:09-27

I am writing a program that takes input from the .csv file. The program run but the problem is it only returns the last line of the .csv file and skips all the other 9 lines. It also does not display the average and the grade. Please help me figure out what I am doing wrong.

Here's the scores.csv file

enter image description here

#include <iostream>
#include <fstream>

using namespace std;
int testScore1, testScore2, testScore3, testScore4, testScore5;
double avg;
char grade;

double getAvg(int testScore1, int testScore2, int testScore3, int testScore4, int testScore5){
    avg = (testScore1   testScore2   testScore3   testScore4   testScore5)/5;
    return avg;
}
char getGrade(double avg){
    if (avg >= 90){
        grade = 'A';
        cout << 'A' << endl;
    }else if (avg >= 80){
        grade = 'B';
        cout << 'B' << endl;
    }else if (avg >= 70){
        grade = 'C';
        cout << 'C' << endl;
    }else if (avg >= 60){
        grade = 'D';
        cout << 'D' << endl;
    }else{
        grade = 'F';
        cout << 'F' << endl;
    }
    return grade;
}

int main(){
    
    ifstream myFile;
    myFile.open("scores.csv");
    
    
    if(!myFile.is_open()){
        cout << "Error" << endl;
    }
    string testScore1, testScore2, testScore3, testScore4, testScore5;
    while (myFile.good()) {
        
        getline(myFile, testScore1, ',');
        getline(myFile, testScore2, ',');
        getline(myFile, testScore3, ',');
        getline(myFile, testScore4, ',');
        getline(myFile, testScore5, '\n');

    }
    
        cout<< setw(15) <<" Test scores"<<endl;
        cout<<"--------------------"<<endl;
        cout<< " 1   2   3   4   5   Avg  Grade"<<endl;
        cout<<"=== === === === === ===== ====="<<endl;
        cout<< " "<< testScore1<< "  "<< testScore2 << "  "<< testScore3 << "  "<< testScore4 << "  "<< testScore5<< "  " << getAvg << "  " << getGrade <<endl;


    return 0;
}

CodePudding user response:

You print the values outside of the while loop, meaning you never save the previous values. Your program is essentially saying:
"Set t1 to test score row 0, col 0, set t2 to row 1, col 0, etc..."
The loop restarts, and now it goes:
"Set t1 to test score row 0, col 1, set t2 to row 1, col 1, etc..."
Do you see the problem? You overwrite the variables each time the loop runs, without saving them. The program then only prints the final line, because that's what the variables are when the loop ends.

You probably want to solve this by using a 2D array. Then, you can use a nested loop to set each spot to the corresponding value. Is that enough information to figure out the rest? If not let me know.

general idea:

new int[amount of rows][amount of cols] array;
for(int i = 0; i = amount of rows; i )
for(int j=0; j=amount of cols; j )
array[i][j] = getline code here
close loops.

  • Related