gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:38:32 26 4
gpt4 key购买 nike

我正在用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com