+ 1
How do I take inputs in 'for loop' under new variables created at instant based on need
So basically my teacher told me to make a program to take in inputs from students asking their subject marks so I went a step ahead and tried creating a program wherein I ask how many subjects they have (variable x ) and ask them to write all the subjects name of (x)subjects so I made this in for loop but when I'm taking in their subjects name I have no where to store it so I need to create new variables while the program is running which I dont know how to do , thanks in advance anyone who's helping https://code.sololearn.com/cTk2CNiOz2ad/?ref=app
3 Respuestas
0
/*
Create two structs. One will hold the number of subjects and an array of the subjects and marks.
The second will hold the subject name and mark.
*/
#include <stdio.h>
#define MAX_SUBJECTS 20
#define MAX_SUBJECT_NAME_LENGTH 51
int main(void){
typedef struct{
char subject_name[MAX_SUBJECT_NAME_LENGTH];
int mark;
} mark_t;
typedef struct{
int number_of_subjects;
mark_t marks[MAX_SUBJECTS];
} subject_t;
//Initialize your instance of the struct
subject_t subjects = {0};
printf("Enter the number of subjects you have (Must be a number): ");
scanf("%d", &subjects.number_of_subjects);
//Leave out the '=' in '<=' indicies start at 0
for (int i = 0; i < subjects.number_of_subjects; i++){
printf("Enter your subject name\n(This is a string only 50 charaters allowed, more will crash the program):");
//There is not error catchin in this code can crash if 51 chars or more are entered.
scanf("%s", subjects.marks[i].subject_name);
printf("Enter the mark for %s\n(This must be a whole number a double or float will cause undefined behavior)", subjects.marks[i].subject_name);
scanf("%d", &subjects.marks[1].mark);
}
//Now you can do some stuff with the subjects and mark and the number of subjects
return 0;
}
0
Martin: Great points. I would add thought that each indices of the array cannot have a different size char*. Though the lengths of the strings inside the indices may be different the allocated memory will be the same size for each indices of the array.
Great conversation.