gpt4 book ai didi

C - 打印阵列工作不正常

转载 作者:太空宇宙 更新时间:2023-11-04 02:39:11 25 4
gpt4 key购买 nike

我正在编写有关将年级/学号 (KAS)/学生姓名插入数组的代码

然后未知数量的输入在最后打印出来

ISSUE: The issue of my project is that on printing results there are some faulty elements on printing .

我试图检查我在输入后的确切时间插入的每个元素(使用 printf(...) )一切似乎都很好。

但在输出中仍然有一些是错误的。

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

int main()
{
int grade[100] , KAS[100] ,x,spots = 0; // KAS = student number
char name[spots][14], answer;

printf("Please insert a grade : ");
scanf("%d", &grade[spots]);
getchar();

printf("Please add a KAS : ");
scanf("%d",&KAS[spots]);
getchar();

printf("Please enter a name : ");
scanf("%s",&name[spots]);
getchar();

printf("\nDo you want to add another value? y/n : ");
scanf("%c",&answer);
puts("");
getchar();

while(answer == 'y')
{
spots++;

printf("Please insert another grade : ");
scanf("%d", &grade[spots]);
getchar();

printf("Please add another KAS : ");
scanf("%d",&KAS[spots]);
getchar();

printf("Please enter another name : ");
scanf("%s",&name[spots]);
getchar();


printf("\nDo you want to add another value? y/n : ");
scanf("%c\n",&answer);
puts("");
getchar();

if(answer == 'n')
{
break;
}
}
puts("*****************************");
for(x = 0; x < spots; x++)
{
puts("");
printf("%d. Student's great : %d\n",x,grade[x]);
printf("%d. Student's KAS : %d\n",x,KAS[x]);
printf("%d. Student's name : %s\n",x,name[x]);
}
puts("\n*****************************\n");
}

最佳答案

char name[spots][14];         //as spots is 0 , it would be name[0][14]
/* you would end up access invalid memory and cause UB */

您需要将其更改为 -

char name[100][14];

同时在循环内部和循环之前的两个语句中获取输入时-

scanf("%s",&name[spots]);
^ you don't need to use &

并且也在 for循环使用 x <= spots作为循环条件。

关于C - 打印阵列工作不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33827022/

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