链表中的 C++ 字符数组

C++ Character Arrays in Linked Lists

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

输入:

Black Duck
58
Green Hen
33

输出如下所示:(我不希望这种情况发生)

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] = "[=12=]";
int InitCount = 0;

node * CurrentRecordPointer = NULL;
char NextChar= '[=12=]';
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。所以当你 cin 它时,你所有的节点都指向这个字符串,并显示它。

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

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