【问题标题】:How to print a set number of strings to output? C++如何打印一组要输出的字符串? C++
【发布时间】:2014-10-26 23:23:21
【问题描述】:

我很难从 2 个单独的链表中打印数据。我有正确的宽度和缩进。我只是不知道如何让数据每行只打印 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 不能用于确定何时结束一行。

【问题讨论】:

  • 变量temp 是不必要的,left 是未定义的。
  • 此代码似乎重复输出字符串print_data,次数由node_noth 节点的data 成员指定。这是你的意图吗?

标签: c++ printing cmd linked-list iostream


【解决方案1】:

如果我正确理解了您的问题,那么在您的 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;
    }
}

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

【讨论】:

  • 是的,这正是我的问题。但是我对流的 iword() 有点困惑?
  • iword() 只是提供对int 的引用的访问,该引用与作为参数传递的索引相关联(我在第二次使用时不小心省略了它)。最初,int 将具有值0,在上面的代码中,它仅用于计算一个单词被打印的次数。
  • 最后只是使用了使用函数跟踪字数的想法,每次我打 8 个字或每次完整打印后计数都会重置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多