gpt4 book ai didi

c - 程序不接受来自控制台的字符串输入

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:31 26 4
gpt4 key购买 nike

我是 C 编程新手。我正在尝试运行这个程序,它接受用户的人名,并将这些名字存储在一个结构数组中。

输入名称的消息会打印在控制台上,但在用户输入字符串之前,会显示下一条语句。前卫是-

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

//10 students taken in per batch
#define NUMBER_OF_SEATS 10
#define ROLL_NUM 4

//5 faculty members teach every batch
#define NUMBER_OF_FACULTY 5
#define LENGTH_OF_NAME 50


int main ()
{
//Details of a department
struct dept
{
char faculty[NUMBER_OF_FACULTY][LENGTH_OF_NAME];
int id_students[ROLL_NUM];
char students[NUMBER_OF_SEATS][LENGTH_OF_NAME];

};

struct dept batch2010[NUMBER_OF_SEATS];
struct dept *point_batch2010 = batch2010;

//Printing the size of the defined strucutre
printf("%lud",sizeof(struct dept));


for (int i = 0; i<NUMBER_OF_FACULTY; i++)
{
printf("\nEnter name of faculty %d teaching batch of 2010\n",i+1);
gets(*point_batch2010->faculty);
point_batch2010++;
}
printf("\n\n");
point_batch2010 = batch2010;

printf("\nFaculty members are:\n");
for (int i = 0; i<NUMBER_OF_FACULTY; i++)
{
puts(*point_batch2010->faculty);
point_batch2010++;
}
point_batch2010 = batch2010;

**for (int i = 0; i<NUMBER_OF_SEATS; i++)
{
printf("\nEnter name of student studying in batch of 2010");
fgets(*point_batch2010->students, LENGTH_OF_NAME, stdin);
printf("\nEnter roll number of student %d studying in batch 0f 2010\n",i+1);
scanf("%d",point_batch2010->id_students);
}**

for (int i = 0; i<NUMBER_OF_SEATS; i++)
{
puts(*batch2010[i].students);
}
return 0;
}

控制台上的错误是 -

Enter name of student studying in batch of 2010Anita
Enter roll number of student 1 studying in batch 0f 2010
1234
Enter name of student studying in batch of 2010
Enter roll number of student 2 studying in batch 0f 2010
3467
Enter name of student studying in batch of 2010
Enter roll number of student 2 studying in batch 0f 2010

我猜这个错误与 '\n' 字符有关,我可以将代码分成 2 个不同的 for 循环,但问题可以在这个循环本身内进行排序吗?

谢谢。

最佳答案

Faculty 是二维数组。你可以在你的循环中尝试这样的事情,从控制台询问输入。

gets(point_batch2010->faculty[i]);

关于c - 程序不接受来自控制台的字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16942864/

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