链表中的c++字符数组
C++ Character Arrays in Linked Lists
我正在用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);
...
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?