0

I am trying to take in a lot of data from multiple files and I use getline() to take the entire line to put it into a temporary string value and turn the data from the line into an object(everything is already sorted).

void charts(vector<Song> &data, int menuop){
  ifstream stream;
  if(menuop == 1){
    stream.open("charts_top50_1960_1980.csv");
    assert(stream.fail() == false);
    data.clear();
  }
  else if(menuop == 2){
    stream.open("charts_top50_1981_2000.csv");
    assert(stream.fail() == false);
    data.clear();
  }
  else if(menuop == 3){
    stream.open("charts_top50_2001_2020.csv");
    assert(stream.fail() == false);
    data.clear();
  }
  string tempstring;
  while(getline(stream, tempstring)){
    for(int i = 0; i < tempstring.length(); i++){
      if(tempstring[i] == '/'){
        tempstring[i] == ',';
      }
    }
    //cout << tempstring << endl;
    Song tempsong(const &tempstring);
    data.push_back(tempsong);
  }
  stream.close();
}
  • Answer for the title: Yes. `std::string` in C++ can store arbitrary sequences of bytes (including ones that contain 0x00), so any data (including combinations of multiple values) that can be represented as a file can be represented as a string variable (unless it is too large to fit into the RAM) . – MikeCAT Mar 29 '22 at 23:29
  • I would avoid putting binary data into `std::string`, and prefer `std::vector` instead -- it's more fit for purpose. `std::string` implies something that is printable. – paddy Mar 29 '22 at 23:30
  • Response was to the first comment which suggested `std::string` is great for anything. – paddy Mar 29 '22 at 23:32
  • Information can be encoded into a string, and then the function can parse that string to retrieve the information. That makes a few sacrifices (time to encode data into the string or decode data from it, error detection and handling [e.g. if some required information is omitted from the passed string] must be performed at run time not compile time). – Peter Mar 29 '22 at 23:43

1 Answers1

1

Simply change:

Song tempsong(const &tempstring);

to:

Song tempsong(tempstring);

And then make sure Song has a constructor that takes a const string& parameter. Then you can have that constructor split the string on ',' characters and use the substrings as needed. There are plenty of other questions on StackOverflow that explain how to do that, for instance:

Parse (split) a string in C++ using string delimiter (standard C++)

Splitting a C++ std::string using tokens, e.g. ";"

How do I iterate over the words of a string?

Just to point out a few.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770