【问题标题】:How can I stop ostringstream (oss) from adding to/overwriting predefined variables?如何阻止 ostringstream (oss) 添加/覆盖预定义变量?
【发布时间】:2021-07-02 19:19:35
【问题描述】:

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

【问题讨论】:

    标签: c++ ostream


    【解决方案1】:

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

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

    【讨论】:

    • 尽管如此,很少有充分的理由来重用 #2 中的流。所以坚持#1。
    猜你喜欢
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多