链表中的c++字符数组

C++ Character Arrays in Linked Lists

本文关键字:字符 数组 c++ 链表      更新时间:2023-10-16

我正在用c++做一个链表,在一个结构中有两个变量。当我打印列表时,我的代码重复最后一项,即使我输入了不同的项。

输入:

Black Duck
58
Green Hen
33

输出如下:(I don't want this happen)

Green Hen 58
Green Hen 33

代码是:

#include <iostream>
using namespace std;
struct node {
char* item;
int count;
node *link;
 };
//global variable
node * HeadPointer = NULL;
//function prototypes
void Print (node *);
void newItem(char*, int, node *);
int main(){
char InitItem[50] = "";
int InitCount = 0;
node * CurrentRecordPointer = NULL;
char NextChar= '';
char ContinuationFlag = 'Y';
while(toupper(ContinuationFlag) == 'Y'){
    cout << "Enter the description of Item: " <<endl;
    NextChar = cin.peek();
    if (NextChar =='n') {
        cin.ignore();
    }
    cin.get(InitItem, 49);
    cout<<"How many: "<<endl;
    cin>>InitCount;
    CurrentRecordPointer = new node;
    newItem(InitItem, InitCount, CurrentRecordPointer);
    HeadPointer = CurrentRecordPointer;
    cout <<"Do you want to enter more items?" <<endl;
    cout <<"Enter 'Y' or 'N'" <<endl;
    cin  >> ContinuationFlag;
        }
 Print(HeadPointer);
return 0;
  }
//functions
void newItem (char* InitItem, int InitCount, node *CurrentRecordPointer)    {
CurrentRecordPointer->item = InitItem;
CurrentRecordPointer->count = InitCount;
CurrentRecordPointer->link = HeadPointer;

}

void Print (node * Head)
{
while(Head !=NULL) {
cout<< Head->item<<" " << Head->count <<endl;
Head = Head -> link;
   }
 }

我希望输出看起来像这样:

Black Duck 
58
Green Hen
33

我知道这是我对指针的使用。我只是不知道用什么来代替它。如果有人能帮我解决这个问题,我将不胜感激。

这是因为所有节点共享同一项。你只有一份InitItem。因此,当您调用它时,所有的节点都指向这个字符串,并显示它。

尝试为while循环中的每个节点动态创建一个新项:

...
char * InitItem = new char(50);
cin.get(InitItem, 49);
...