正在将格式设置从一个流复制到另一个流

Copying format settings from one stream to another

本文关键字:一个 复制 另一个 格式 设置      更新时间:2023-10-16

我正在为我的类编写一个打印方法,比如:

std::ostream& operator<<(std::ostream& stream, const MyClass& M);

在内部,我需要创建一个中间stringstream,以便稍后将我得到的字符串放在stream中的正确位置。但stream可能有一些非默认设置,如精度、字段宽度、数字格式等

如何将所有此类格式设置从stream复制到我的stringstream,而无需手动对每个设置进行"读取和设置"?

您可以使用copyfmt()将格式选项从一个流复制到另一个流:

std::ostream& operator<<(std::ostream& stream, const MyClass& M) {
    std::ostringstream tmp;     // temporary string stream
    tmp.copyfmt(stream);        // COPY FORMAT of origninal stream
    ...                         // rest of your code
    }

一次复制所有格式选项,例如:

MyClass o; 
...
std::cout.fill('*');
std::cout.width(10);
std::cout << o<<std::endl;    // stringstream rendering would use fill and width here 
std::cout << std::hex << o << std::dec <<std::endl;  // and even hex conversion here