c ++输出并输入单个字符

时间:2009-02-20 06:30:48

标签: c++ list linked-list char cout

我正在用c ++编写一个程序,它实现了一个双向链表,每个节点都有一个字符。我通过追加函数插入字符:

doubly_linked_list adam;
adam.append('a');

此功能实现如下:

//Append node
    node* append(const item c){

        //If the list is not empty...
        if(length){
            //maintain pointers to end nodes
            node* old_last_node = last;
            node* new_last_node = new node;

            //re-assign the double link and exit link
            old_last_node->next = new_last_node;
            new_last_node->back = old_last_node;
            new_last_node->next = NULL;

            //re-assign the last pointer
            last = new_last_node;
        }
        //If this is the first node
        else{
            //assign first and last to the new node
            last = first = new node;

            //assign nulls to the pointers on new node
            first->next = first->back = NULL;
        }

        //increase length and exit
        ++length;
        return last;
    }

但是,我认为存在一个问题,可能是C ++处理字符的方式。当我去打印我的列表时,不知怎的,我从来没有得到我已经附加到列表中的字符。这就是我用来打印的内容:

//Friendly output function
    friend std::ostream& operator << (std::ostream& out_s, const doubly_linked_list& source_list){
        //create iteration node pointer
        node* traverse_position = source_list.first;

        //iterate through, reading from start
        for(int i = 1; i <= source_list.length; ++i){
            //print the character
            out_s << (traverse_position->data);
            traverse_position = traverse_position->next;
        }

        //return the output stream
        return out_s;
    }

打印时我得到废话。它会打印我从未附加到列表中的字符 - 你知道,只是来自内存中的某些字符。可能导致这种情况的原因是什么?

3 个答案:

答案 0 :(得分:7)

您在c函数中在哪里分配值append()?我担心你可能过多地集中在双重链接列表部分而不是存储数据部分。 :)

答案 1 :(得分:3)

正如其他人已经提到的那样,你忘记存储你应该附加的字符。这是一个合理的错误。为了将来避免使用它,您可以让编译器帮助您。

大多数编译器提供警告关于技术上可行的事情,但可能不是您真正想做的事情。在您的情况下,您声明了参数c,但您从未使用它。启用警告后,您的编译器可能已经注意到并告诉您没有使用它。这可能已经足以提醒你,你还没有写完这个功能。

GCC启用常见警告的选项是-Wall。 (这是“警告”的“W”加上“全部”;它与墙壁无关。但它并非真正所有警告。)例如:

g++ -Wall list-program.cpp

其他编译器也有类似的选择。有关详细信息,请查看编译器的文档。

答案 2 :(得分:1)

在您的追加方法中,您实际上是否将项目放入新节点中。当你去打印时,它只是打印出该内存位置中发生的任何值(一些随机值)。

相关问题