How does stoi() function work with stringstream in C++?

257 Views Asked by At

So I'm new to C++, so bear with me here. I'm trying to read a csv file and parsing the data into smaller strings to hold in my class. As I attempt t do this, I come across a problem with stoi(). Every time I try to convert my string to an int, I get an error "terminate called after throwing an instance of 'std::invalid_argument' what(): stoi".

I have tried checking to see if my string is an actual number and it is. I have checked if there is a space or any other weird character, there isn't. I'm not sure what's wrong. Guidance will be appreciated.

Edit: Here is my code

class MusicData 
{
  public:
  void setDate(string theDate) {date = theDate;}
  void setRank(int theRank) {rank = theRank;}
  void setSongName(string theSong) {song = theSong;}
  void setArtist(string theArtist) {artist = theArtist;}
  void setLastWeek(int theLastWeek) {lastWeek = theLastWeek;}
  void setPeakRank(int thePeakRank) {peakRank = thePeakRank;}
  void setTotalWeeks(int total) {weeksOnBoard = total;}
  string getDate()  {return date;}
  int getRank() {return rank;}
  string getSong() {return song;}
  string getArtist() {return artist;}
  int getLastWeek() {return lastWeek;}
  int getPeakRank() {return peakRank;}
  int getTotalWeeks() {return weeksOnBoard;}

 private:
 int rank, lastWeek, peakRank, weeksOnBoard;
 string date, song, artist;
};


void readFromFile( const char fileName[], vector <string>& hold )   
{
  MusicData aSong;
  ifstream file;
  file.open(fileName);    
       
  assert(file.fail() == false);    
  string data;
  string date, str_ranks, songName, artist, str_last_week;
  int ranks, lastWeek;
  while (getline(file, data))
  {
    stringstream s(data);

    getline(s, date, ',');
    aSong.setDate(date);

    getline(s, str_ranks, ',');
    ranks = stoi(str_ranks);
  }

  file.close();
}
1

There are 1 best solutions below

0
Martin York On BEST ANSWER

The operator>> will read a stream directly into an integer (you don't need to manually convert it).

  string data;
  int rank;
  while (getline(file, data))
  {
      stringstream s(data);

      // Always check stream operations worked.
      if (getline(s, date, ',')) {
          aSong.setDate(date);     // Why is Date a string.
                                   // Should this not be its own type?

          char sep = 'X';
          if (s >> rank >> sep && sep == ',') {
              aSong.setRank(rank)
          }
      }
  }

Though I would write operator>> for the MusicData class so that it can read its own data from the stream.

  class MusicData
  {
        // STUFF
        friend std::istream& operator>>(std::istream& str, MusicData& value);
  };