c++ - 有什么办法可以将这个函数分开并插入空格吗?

标签 c++ c++11

假设我需要按以下格式将地址输出到屏幕(地址的每一行通过前缀空格字符对齐):

Address: 1234 Elm St.    
         Apartment # 2 Rear  
         Anytown, NV 12345-6789 

This is some example code that defines a free function (printAddress) that will print the address to the screen. I cannot alter the code for the printAddress function in any way.

#include <iostream>
#include <iomanip>

using namespace std;

void printAddress( );

int main( )
{

    cout << "Address: ";
    printAddress ( );

    return 0;
}

void printAddress( ) 
{
    cout << "1234 Elm St." << endl;
    cout << "Apartment #2 Rear" << endl;
    cout << "Anytown, NV 12345-6789" << endl;
};

截至目前,这段代码的输出是:

Address: 1234 Elm St.  
Apartment #2 Rear  
Anytown, NV 12345-6789  

我想知道是否有可能以某种方式将函数分开以在第二行和第三行插入这些空格并使所有内容对齐。有任何想法吗?或者这是不可能的?

最佳答案

您可以重定向 std::cout,重新编写消息,然后将其重新发布到(真实的)std::cout。类似的东西(尚未测试):

ostringstream oss;
auto oldcoutbuf = cout.rdbuf(oss.rdbuf());
printAddress();
string s = oss.str();
s = indentMsg(s);
cout.rdbuf(oldcoutbuf);
cout << "Address: " << s;

(可能被称为“严重可怕的东西让它工作”。)

printAddress 函数设计得很糟糕。

关于c++ - 有什么办法可以将这个函数分开并插入空格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47502120/

相关文章:

指向 const 指针的 C++ 指针

c++ - Variadic 函数不会用 clang 编译

c++ - 如何处理多个线程的重复启动?

c++ - 在类中抛出异常的最佳方式是什么?

c++ - 使用unix下载html文件

c++ - 是否有采用投影函数的 min_element 变体?

java - 线程 "main"java.lang.UnsatisfiedLinkError : A dynamic link library (DLL) initialization routine failed 中的异常

C++——如何从 STL 容器中有效地删除具有这种条件的元素?

c++ - 排列可 move 结构

c++ - 为什么通过通用引用运算符 (&&) 将变量引用传递给可变参数模板函数失败?