如何阻止ostringstream(oss)添加/覆盖预定义变量?

我对 C++ 比较陌生,并且遇到了将ostringstream oss用作在输出中包含变量并将其设置为字符串的方法。

前任。

string getDate(){ 

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

return date;
}

我的问题是,每次我通过对象调用 getDate() 方法时,它都会将先前记录的输出添加到我认为称为“流”的内容中。

前任。

//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;
}

但输出如下:

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

Process finished with exit code 0

有什么方法可以保护 oss 的价值,或者至少让它得到更新而不是添加?

回答

如果要清除流,有两种选择。

  1. 使用本地流
string getDate(){ 
  std::ostringstream oss;
  
  oss << _month << "," << _day << "," << _year ; //date format
  string date = oss.str(); //date as a string

  return date;
}
  1. 使用后清除您的流
string getDate(){ 
  
  oss << _month << "," << _day << "," << _year ; //date format
  string date = oss.str(); //date as a string
  oss.str(""); // clear stream

  return date;
}


以上是如何阻止ostringstream(oss)添加/覆盖预定义变量?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>