c++ - setw 在一个函数中返回一个 ostream

标签 c++ cout ostream setw

这是我的功能

ostream margain(std::string firstWord)
{
    ostream x;
    x << std::setw(20) << firstWord;
    return x;
}

在 main 中我想使用如下函数

std::cout<< margain("start") << "````````````````````````````````````" << std::endl;
// print things out
//then
std::cout<< margain("End") << "````````````````````````````````````" << std::endl;

我得到输出,没有显示开始或结束,返回值为

0````````````````````````````````````

我该如何解决?为什么?

编辑: 我知道是函数导致的,因为如果我添加这个

cout << std::setw(20) << firstWord; in the function, It prints right,

我修复了它,不是最好的方法,但是

调用函数为

margain(std::cout, "End") << "~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~" << endl;

函数看起来像

ostream& margain(ostream& stream, std::string firstWord)
{
    stream << std::left << std::setw(10) << firstWord;
    return stream;
}

谁知道更好的方法?

最佳答案

您打印的是 ostream 的值,而不是 firstword 的值。 ostream x 在这种情况下是一个未打开的流,因此它不会“做”任何事情。因为编译器允许转换为 bool (C++11) 或 void *(C++11 之前),所以会打印该转换的“值”。请注意,对 x 的任何操作都不会影响 cout

我认为最简单的解决方案是实际将 std::setw(20) 添加到您的输出行:

std::cout<< std::setw(20 << "End" << "````````````````````````````````````" << std::endl;

另一种选择是将 std::cout 传递给 margain,然后返回 std::string,像这样:

std::string margain(ostream& x, const std::string& firstWord)
{
    x << std::setw(20);
    return firstWord;
}

那么你可以这样做:

std::cout<< margain(cout, "start") << "````````````````````````````````````" << std::endl;

但它并不完全灵活或“整洁”。

第三种选择当然是有一个 MarginString 类:

class MarignString
{
  private:
     int margin;
     std::string str;
  public:
     MarginString(int margin, std::string str) margin(margin), str(str) {}
     operator std::string() { return str; }
     friend std::ostream& operator(std::ostream& os, const MarginString& ms);
 };


 std::ostream& operator(std::ostream& os, const MarginString& ms)
 {
     os << std::setw(ms.margin) << ms.str;
     return os;
 }

 ...
 std::cout<< MarginString(20, "start") << "````````````````````````````````````" << std::endl;

请注意,最后一种方法可能也不是那么好……;)

关于c++ - setw 在一个函数中返回一个 ostream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18638594/

相关文章:

c++ - Makefile/C++ 类 : Makefile error for C++? 或者类定义错误?

c++ - 多参数宏定义错误

c++ - cout中的 "uR"是什么意思?

c++ - 为什么cout会阻止后续代码在这里运行呢?

c++ - C++函数将返回值放在哪里

c++ - 仅计算 "core"QImage 数据(不包括元数据)的 QCryptographicHash

c++ - 不明白为什么这个 std::cout 打印这个

c++ - 我应该什么时候返回 std::ostream?

C++ 重载 ostream 和 istream 运算符

c++ - 如何在 C++ 中编写 ofstream vector ,它接收所有不同的输出流,如 cout、字符串流和 ofstream