【发布时间】:2020-03-10 10:42:04
【问题描述】:
我编写了一个链表程序,想用空格输入,但它不起作用。当我简单地将“scanf”与 %s 一起使用时它工作正常,但由于我想用多个空格输入,所以我尝试使用“ gets" 和 "puts" 我也尝试过使用 scanf("%[^\n]*c");但在控制台上它给了我随机垃圾值 scanf("%[^\n]*c");对于“获取”,它读取空白,
现在让我告诉你们一些有关代码及其工作原理的信息
createNode(); 函数基本上只是创建一个新节点来存储在列表中,并将这个新创建的节点的地址返回给insertend(); 函数,它在列表末尾和start=t=newnode 中对齐新节点@start是指向第一个节点的头指针,t 用于遍历列表,直到 t 的值变为 NULL,正如您在 insertend(); 函数的 else 部分中看到的那样,我们正在使用另一个指针 @ 987654332@ 并将 start 的值存储在其中,这样我们就可以遍历列表而不会丢失最初保存在 start 指针中的第一个节点的地址。
这是代码->
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct Node
{
char first[20];
struct Node* next;
};
struct Node* start=NULL;
struct Node* t,*u;
int i=1;
struct Node* createNode() //this function creates a newnode everytime it's called
{
struct Node* create=(struct Node*)malloc(sizeof(struct Node));
return create;
}
int length() //to measure the length of the list.
{
int count = 0;
struct Node* temp;
temp=start;
while(temp!=NULL)
{
count++;
temp = temp->next;
}
return count;
}
void insertend() //to insert a node at the end of the list.
{
int l;
struct Node* newnode = createNode();
printf("Enter Name : ");
fgets(newnode->first,sizeof(newnode->first),stdin);
if(start==NULL)
{
start=t=newnode;
start->next=NULL;
}
else
{
t=start;
while(t->next!=NULL)
t=t->next;
t->next=newnode;
t=newnode;
t->next=NULL;
printf("%s successfully added to the list!",newnode->first);
}
l=length();
printf("The length of the list is %d",l);
}
void display() //to display the list
{
struct Node* dis;
dis=start;
if(start==NULL)
{
system("cls");
printf("No elements to display in the list");
}
else
{
system("cls");
for(int j=1;dis!=NULL;j++)
{
printf("%d.) %s\n",j,dis->first);
dis=dis->next;
}
}
}
int menu() //this is just a menu it returns the user input to the main function
{
int men;
printf("Please select a choice from the options below :-\n\n");
printf("1.) Add at the end of the list\n");
printf("2.) Display list\n");
printf("3.) exit\n");
printf(" Enter your choice : ");
scanf("%d",&men);
return men;
}
int main()
{
while(1)
{
system("cls");
switch(menu())
{
case 1 : insertend();
break;
case 2 : display();
break;
case 3: exit(0);
default : system("cls"); printf("Ivalid choice!Please select an appropriate option!");
fflush(stdin);
break;
}
getch();
}
return 0;
}
【问题讨论】:
-
请提供minimal verifiable example。例如,我们不知道
struct Node和createNode的定义。任何一个都可能有(也可能没有)错误。 -
阅读gets标签的描述并注意警告。
-
提供完整代码!
-
C 语言中不再有函数
gets。您需要用过去 20 年更新的学习资源替换当前的学习资源。 -
欢迎来到 Stack Overflow!请edit您的代码将其减少为您的问题的minimal reproducible example。您当前的代码包含许多与您的问题无关的内容 - 因为您询问的是
scanf(),所以您无需使用任何链表代码来给我们带来负担。
标签: c data-structures linked-list gets puts