gpt4 book ai didi

c - 通过动态分配的结构变量获取用户输入的字符串

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

我的名字变量是一个固定变量,位于学生结构内。

当我运行代码时,输​​入部分会跳过名称,或者事实上,无论我在哪个字符变量中放置空格,都会跳过下一个字符输入。代码如下:

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

struct student{
char name[50];
char roll[10];
char batch[20];
long int mob;
};
struct student *stud;
int main()
{
int num,i;
printf("Enter the number of students in the class: ");
scanf("%d",&num);
printf("Enter the following records: ");
FILE *fp;
fp = fopen("student.txt", "w");
for (i=0;i<num;i++)
{
stud = (struct student *)malloc(sizeof(struct student)*num);
printf("\nStudent %d: ",i+1);

printf("\nEnter Name: ");

scanf("%s",stud->name);

printf("\nEnter Roll No.: ");
scanf("%s",stud->roll);
printf("\nEnter Batch: ");
scanf("%s",stud->batch);
printf("Enter mobile number: ");
scanf("%ld",&stud->mob);
fprintf(fp,"%s %s %s %ld",stud->name,stud->roll,stud->batch,stud->mob);
}
fclose(fp);
return 0;
}

最佳答案

scanf 一旦遇到空格就会停止读取字符。最好使用fgets

fgets(stud->name, 50, stdin);  

请注意,如果输入字符少于数组大小,fgets 也会读取 '\n' 字符。你需要照顾好这一点。

关于c - 通过动态分配的结构变量获取用户输入的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35091845/

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