gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:26:47 24 4
gpt4 key购买 nike

我是 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 的值(value),或者至少让它得到更新而不是添加?

最佳答案

如果你想清空你的流,有两种选择。

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

关于c++ - 如何阻止 ostringstream (oss) 添加/覆盖预定义变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66978268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com