gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:54:21 25 4
gpt4 key购买 nike

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

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/

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