gpt4 book ai didi

c - 处理字符串的链表,C

转载 作者:行者123 更新时间:2023-11-30 19:07:07 25 4
gpt4 key购买 nike

我试图从用户那里获取输入(单词/字符串)并将其存储在我的链接列表中,但是当我打印列表时,程序结束。我对 C 语言非常陌生,任何对我有帮助的建议或文章将不胜感激!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
int data, index;
char text[255];
struct node* next;
};

//Global Variables
struct node* root = NULL;

//Prototypes
void insertA();
void insertB();
void prn();

//Main
void main () {
char command[4];
int num;
char text[255];

while(1) {
printf("Command? "); //assume we know the key words
fflush(stdout);
scanf("%s", &command);

//Reads input and selects which command to execute
if (strcmp(command, "insertA")==0) {
scanf("%s", &text);
insertA(text);
} else
if(strcmp(command, "insertB")==0) {
scanf("%s", &text);
insertB(num);
} else
if (strcmp(command, "prn")==0) {
prn();
} else
if (strcmp(command, "end")==0) {
exit(1);
}
else {
return;
}
}
}

//Command Insert After
void insertA(char* text) {
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));

temp->data = text;
temp->next = NULL;

//Function if link does not exist, creates one
if(root==NULL) {
root = temp;
printf("Text inserted at beginning\n");
}
//If link exists, adds to the end
else {
struct node* p;
p = root;

while(p->next != NULL) {
p = p->next;
}
p->next = temp;
printf("Ok\n");

}
}

//Command Insert Before
void insertB(char* text) {
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = text;
temp->next=NULL;
//Function if link does not exist, creates one
if (root == NULL) {
root = temp;
printf("Text inserted at beginning\n");
fflush(stdout);
}
//If link exists, add to beginning
else {
temp->next=root;
root = temp;
printf("Ok\n");
fflush(stdout) ;
}
}

//Command Print
void prn() {
struct node* temp;
temp = root;
int i=1;

if(temp == NULL) {
printf("List is empty\n");
fflush(stdout);
}
else {
while(temp != NULL) {
printf("%d. ", i);
printf("%s\n",temp->data);
temp = temp->next;
i++;
}
printf("\n");
}
}

我将附上我得到的输出的屏幕截图 here这样你就可以看到发生了什么

最佳答案

您的命令缓冲区只有 4 个字节 - “insertA”如何适应它?

您正在使用scanf()来获取命令。当您按 Enter 键时,scanf() 将使用 '\n' 分隔字符串填充输入缓冲区,然后当它通过循环进行第二轮时,您的下一个scanf 将首先读取换行符,而不是您想要测试的任何命令。

如果您想安全地重用 text 缓冲区,请增加其大小并使用 fgets() 读取您的输入。

关于c - 处理字符串的链表,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47117094/

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