How can I stop ostringstream (oss) from adding to/overwriting predefined variables?

Viewed 65

I'm relatively new to C++ and have come across the use of ostringstream oss as a way to include variables in an output and set it as a string.

Ex.

string getDate(){ 

oss << _month << "," << _day << "," << _year ; //date format
string date = oss.str(); //date as a string

return date;
}

My issue is that every time I call the method getDate() through an object, it adds the previously recorded output into, what I believe is called the "stream."

Ex.

//private variables w default values
int _day{-1};
int _month{-2};
int _year{-3};

int main() {
//init objects
    Bday nothing{};
    Bday Clyde (12,24,1993);
    Bday Harry("Harry",11,05,2002);

//outputs

//expected to return default values (-2,-1,-3)
    cout << "Default Values: "<< nothing.getDate() << endl; 

//expected to return Clyde's date only: 12,24,1993
    cout << "Date Only: " <<  Clyde.getDate() << endl;

// expect to return Harry's date: (11,05,2002) 
    cout << "Harry's Bday: " << Harry.getDate()  << endl;

    return 0;
}

But instead the output is the following:

Default Values:
Date Only: -2,-1,-3
Harry's Bday: -2,-1,-312,24,1993

Process finished with exit code 0

Any way to protect the value of oss or at least make it so that it gets updated rather than added to?

1 Answers

If you want to clear your stream, there are two choices.

  1. Use local stream
string getDate(){ 
  std::ostringstream oss;
  
  oss << _month << "," << _day << "," << _year ; //date format
  string date = oss.str(); //date as a string

  return date;
}
  1. Clear your stream after use
string getDate(){ 
  
  oss << _month << "," << _day << "," << _year ; //date format
  string date = oss.str(); //date as a string
  oss.str(""); // clear stream

  return date;
}
Related