如何阻止 ostringstream (oss) 添加 to/overwriting 预定义变量?
How can I stop ostringstream (oss) from adding to/overwriting predefined variables?
我是 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 的价值,或者至少让它得到更新而不是添加?
如果你想清除你的流,有两种选择。
- 使用本地流
string getDate(){
std::ostringstream oss;
oss << _month << "," << _day << "," << _year ; //date format
string date = oss.str(); //date as a string
return date;
}
- 使用后清除您的流
string getDate(){
oss << _month << "," << _day << "," << _year ; //date format
string date = oss.str(); //date as a string
oss.str(""); // clear stream
return date;
}
我是 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 的价值,或者至少让它得到更新而不是添加?
如果你想清除你的流,有两种选择。
- 使用本地流
string getDate(){
std::ostringstream oss;
oss << _month << "," << _day << "," << _year ; //date format
string date = oss.str(); //date as a string
return date;
}
- 使用后清除您的流
string getDate(){
oss << _month << "," << _day << "," << _year ; //date format
string date = oss.str(); //date as a string
oss.str(""); // clear stream
return date;
}