如何打印一组要输出的字符串?C++

How to print a set number of strings to output? C++

本文关键字:输出 C++ 字符串 何打印 打印 一组      更新时间:2023-10-16

我很难从两个单独的链表中打印数据。我有合适的宽度和缩进。我只是不知道如何让数据每行只打印8个字符串。

我的打印功能

void print(string print_data, int node_no) {
    Node* p = head;
    Node* temp;
    int i;
    int number = node_no;
    if(node_no == 0 || node_no == 1) {
        temp = p;
    }
    else {
        i = 1;
        while(i < node_no) {
            i = i +1;
            temp = p->next;
            p = p->next;
        }
    }
    cout << left;
    for(int i = 0; i < temp->data; ++i) {
        cout << setw(4) << print_data << " ";
    }
}

此外,我不能通过使用模b/c来设置这一点。我一次从每个列表中打印一个节点,所以我在for循环中的I不能用来确定何时结束一行。

如果我正确理解您的问题,那么在执行print()函数底部的循环时,您不知道给定行上已经打印了多少字符串。如果这就是问题所在,那么您需要将关于有多少字符串已经在某个地方的行中的信息存储起来。存储该数据的一个位置可以是流的iword():

// at an appropriate location, probably at namespace scope outside the function:
static int const iword_index = std::ios_base::xalloc();
// ...
for(int i = 0; i < temp->data; ++i) {
    out << setw(4) << print_data << " ";
    if (++out.iword(iword_index) == 8) {
        out << 'n';
        out.iword(iword_index) = 0;
    }
}

原则上,也可以创建一个适当的过滤流缓冲区,它跟踪每行的字数。虽然这是一个更通用的解决方案,但也有点复杂。