Reputation: 70
I am writing a code about inserting a grade / student number (KAS) / Name of the student into arrays
And the after unknown number of inputs print them in the end
ISSUE: The issue of my project is that on printing results there are some faulty elements on printing .
I tried to check every element that I inserted the exact time after I made an input ( with a printf(...)
)
and everything seemed fine.
But still in the output some of them were wrong .
#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");
}
Upvotes: 1
Views: 316
Reputation: 1
Your Code is alright. There are just a few mistakes there.
1. initialize array by writing static int grade[ ]
...
2.Remove getchar
before if(answer == 'n')
statement.
3.The condition in for loop should be x <= spots
. This is the reason that if you enter 2 student names, it prints name/record of only one student.
Hope it helped :)
Upvotes: 0
Reputation: 16607
char name[spots][14]; //as spots is 0 , it would be name[0][14]
/* you would end up access invalid memory and cause UB */
You need to change this to -
char name[100][14];
And also while taking input in both statements inside and before loop-
scanf("%s",&name[spots]);
^ you don't need to use &
And also in the for
loop use x <= spots
as loop condition.
Upvotes: 2