Beginner programming including arrays and I'm having trouble just getting user input for the arrays. The printf functions I've included are just to check whether my arrays are working, the larger program I'm writing just needs to use these two arrays.
The input for the char array seems to work fine, I've tried a couple of different methods. However, the int array doesn't seem to work using the same diversity of methods I've used successfully with the char array. Not sure what I'm missing. Below is the code and the output when I run the program:
int main()
{
char grades[5]; // create array to store letter grades
int hours[5]; // array to store hours
puts("Please enter letter grades:"); // Input letter grades using fgets
fgets(grades, 5, stdin);
printf("Letter grade for course 3 is %c.\n", grades[2]);
int x = 0;
puts("Please enter course hours:\n");
for (x = 0; x < 5; x++)
{
scanf("%d", &hours[x]);
}
printf("Course hours for course 2 are: %d.\n", hours[1]);
return 0;
}
Output of this code:
Please enter letter grades:
ABCDF <- user input
Letter grade for course 3 is C.
Please enter course hours:
Course hours for course 2 are: -858993460.
Press any key to continue . . .
fgetsshould be allowed to read the newline which will be stored in the array, so the array should be at leastchar grades[7];to allow for the newline and the string terminator.fgetsshould be passedsizeof gradesas the length. As it is, data is left in the input buffer which upsets the following inputs. - Weather Vanefgets(), and if it is important for your program flow, check whether a complete line was read (seach for the newline character) - 2.) Almost always, do not usescanf(). You could usesscanf()on a line read byfgets()or some simpler methods, see also my beginners' guide away fromscanf(). - user2371524