【发布时间】:2026-01-26 13:55:02
【问题描述】:
我的struct Node 下有一个名为flavour 的字符串变量,每次我输入风味变量的字符串时,程序都会停止工作并最终什么也不打印。我已经通过使用不同的变量类型(例如整数和字符)对其进行了测试,这两种变量类型都可以正常工作,并且会打印出变量中的任何内容。
这是我的代码:
#include <iostream>
using namespace std;
struct Node {
string flavor;
struct Node *next;
};
struct Node* head = NULL;
void insert(string data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->flavor = data;
new_node->next = head;
head = new_node;
}
void display() {
struct Node* ptr;
ptr = head;
while (ptr != NULL) {
cout<<"First data is "<< ptr->flavor;
ptr = ptr->next;
}
}
int main() {
string input;
cout<<"Enter a flavor!"<<endl;
cin>>input;
insert(input);
cout<<"The linked list is: ";
display();
return 0;
}
这是结果,您可以看到cin>>input; 或insert(input) 之后的所有内容似乎都不起作用。我错过了什么吗?
【问题讨论】:
-
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));啊!我的眼睛!
标签: c++ string list oop linked-list