'I keep gettin an stoi conversion error when trying to open a file

So im trying to read a file's contents but everything I run the program I get an error stating

libc++abi: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion

I cant seem to figure out why it's giving me that error. When I input the file name and hit enter I get this error.

void displayGrades(string fileInput, vector<GradeItem> &content) {
  ifstream myFile(fileInput);
  string date, description, type, tempG, tempMG, line;
  int grade, maxGrade;

  std::getline(myFile, line);
  while(std::getline(myFile, line)){
    std::istringstream iss(line);

    std::getline(iss, date);
    std::getline(iss, description);
    std::getline(iss, type);
    std::getline(iss, tempG);

    grade = stoi(tempG);

    std::getline(iss, tempMG);
    maxGrade = stoi(tempMG);

    GradeItem G(date, description, type, grade, maxGrade);
    content.push_back(G);
  }
}

File contents:

Date, Description, Type, Grade, MaxGrade
04/13/2022,Today is a good day,quiz,100,1

Any help would be nice!

c++


Solution 1:[1]

std::getline when not provided by a delimiter reads the whole line of the input stream.

So, what's happening here is that you are reading the whole line in the file into the date variable, while the other strings remain empty.

To correct this, you can add a third argument to the std::getline function which is a delimitation character that tells the function to stop reading further input after reaching this character(here ',').

Here is an example:

std::getline(iss, date, ',');

Your modified code should be:

void displayGrades(string fileInput, vector<GradeItem> &content) {
  ifstream myFile(fileInput);
  string date, description, type, tempG, tempMG, line;
  int grade, maxGrade;

  std::getline(myFile, line);
  while(std::getline(myFile, line)){
    std::istringstream iss(line);

    std::getline(iss, date, ',');
    std::getline(iss, description, ',');
    std::getline(iss, type, ',');
    std::getline(iss, tempG, ',');

    grade = stoi(tempG);

    std::getline(iss, tempMG);
    maxGrade = stoi(tempMG);

    GradeItem G(date, description, type, grade, maxGrade);
    content.push_back(G);
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SudhanshuSuman