C++ -- Column Formatting

C++ -- Column Formatting

本文关键字:Formatting Column C++      更新时间:2023-10-16

在过去的几个小时里,我一直在为此苦苦挣扎,但我需要帮助格式化一些输出。基本上,我有一个二维数组arr,我想以 3 X 70 组打印,即

aaaaaa ... a //Columns 1-70
bbbbbb ... b //Columns 1-70
cccccc ... c //Columns 1-70
             //newline
             //newline
             //newline
aaaaaa ... a //Columns 1-70
bbbbbb ... b //Columns 1-70
cccccc ... c //Columns 1-70
//and so on like that until all of top, mid, and bot is printed out

其中aaaa....a对应于arr[0]bbbbb....b对应于arr[1]cccc...c对应于arr[2]

另一部分是arr对应于三个一维数组topmidbot。正如您可能猜到的那样,aaaa...aaatop中的值,bbbb...bbbmid中的值,ccc....cccbot中的值。topmidbot的长度都相同,因此length一个字段被分配给该值。

我当前的代码是(不包括导入(:

string alignToString;
stringstream out;
char arr[3][70];

for (int column = 1; column <= length; ++column)
{
    out << top[column - 1];
    if (column % 70 == 0)
    {
        out << endl;
        for (int column = 1; column < 70; ++column)
        {
        }
    }
    arr[0][column] = top[column - 1];
    arr[1][column] = mid[column - 1];
    arr[2][column] = bot[column - 1];
    if (column % 70 == 0)
    {
        break;
    }
//TODO: output out.str();
}

显然,此代码不起作用。我的想法是,也许我可以以三列为一组输出每列,一旦列 % 70 = 0,我会添加换行符,但我似乎无法弄清楚。如果有人可以帮助我解决这个问题,或者为这个问题提供更好的解决方案,我将不胜感激。提前谢谢你。

这个问题有点不清楚——arr是用来做什么的?您是否真的想将topmidbot的每一行复制到arr中以供以后使用以及打印?或者这只是您尝试的解决方案的一部分?如果您不需要它用于其他目的,那么将数据从三个数组中复制出来以及您的数据到这些临时缓冲区中没有任何好处。

另一个不明显的一点是,您是想要内存字符串表示形式,还是实际直接打印到cout。如果是后者,那么事先临时写入stringstream缓冲区也没有真正的好处 - 无论哪种方式,字符都将以相同的顺序写入。

我假设您同时打算同时使用两者,但如果不是,则可以使解决方案运行得更快。说到速度,尽管编译器在优化速度方面做得越来越好,但逐个字符的工作可能会非常慢。使用 std::ostream::write(( 一次长距离运行字符更清晰、更快捷。

const size_t maxColumn = 70;
char arr[3][maxColumn];
using CharIteratorPair = std::pair<char *, char *>;
CharIteratorPair myArrays[] = {
    { top, arr[0] },
    { mid, arr[1] },
    { bot, arr[2] }};
std::stringstream out;
for (size_t i = 0 ; i < length; i += maxColumn) {
    size_t gulpSize = std::min(maxColumn, length - i);
    for (auto& source: myArrays) {
        out.write(source.first, gulpSize);
        out << std::endl;
        // Remove this line if you don't need to copy the data
        // into "arr"
        std::copy_n(source.first, gulpSize, source.second);
        std::advance(source.first, gulpSize);
    }   
    // "arr" has now been filled in, do other processing here for each
    // group of three rows as needed
}   
// out has now been filled in, ready for extracting with .str()
// or printing to std::cout etc.
std::cout << out.str();