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

标签 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;
    }

当我打印它时,我就得到了废话。它打印出我从未添加到列表中的字符——你知道,只是来自内存中某处的字符。可能是什么原因造成的?

最佳答案

append() 函数中,您在哪里分配值 c?我担心您可能过于关注双向链表部分而没有足够关注存储数据部分。 :)

关于c++输出和输入单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/568524/

相关文章:

c++ - 在 vector<int> 中定义的索引处从 vector<string> 中删除一个字符串

c++ - 如何在我的vs2010项目中使用wxformbuilder生成的c++文件

c++ - 优化项目冲销

python - 列表项之间的欧氏距离

C 编程错误,打印链表,在运行时执行代码崩溃

c++ - LinkList 代码中的错误

输入值后 C++ 哈希表程序挂起

c++ - 函数指针与直接调用 cout

list - Kotlin 列表中的连续整数组

CSS 列表如果是十六进制则不起作用