Home > Software engineering >  Accessing struct elements based on user input on scanf
Accessing struct elements based on user input on scanf

Time:01-17

I have to access different elements from struct based on what user inputs on scanf.

For example, if a user inputs "grade", I need to pass it on a function, and return the values of struct.grade, but then with the same function, I need to be able to do the same thing with different inputs such as struct.name or struct.id for example.

How can I use the user input from scanf("%s") to the function?

I tried using switch case in my main, to turn different input into different numbers. Grade = 1, name = 2, etc. Then passing it to the functions, with idea of indexing the struct. But then I can't figure out how to access struct elements from given numbers. I tried searching for struct indexing but didn't find anything.

Any other method would be fine though.

Brief code example below

struct class{
    char name[50];
    int score;
    char grade[2];
}data[100];

void function(struct, input){}
// expected function workflow:
// takes the input from the argument,
// example function(data, "grade")
// count unique grades (I have this algorithm already)
// but then I can use the same code for another input such as name.
// the question is how to make my functiom able to access data.grade in this call,
// and the same function able to access data.name in other function call with function(data, "name") as its input?


int main(){
char input[10];
scanf("%s", input); getchar();
// a function that takes input as parameter
return 0;
}

CodePudding user response:

Use strcmp to compare the user's input against certain strings, and branch based on the results.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char input[128];

    printf("Enter a command: ");

    if (!fgets(input, sizeof input, stdin))
        return 1;

    input[strcspn(input, "\r\n")] = 0;

    struct {
        char name[64];
        int score;
        char grade;
    } student = {
        "Dru", 42, 'B'
    };

    if (0 == strcmp(input, "name"))
        printf("%s\n", student.name);
    else if (0 == strcmp(input, "score"))
        printf("%d\n", student.score);
    else if (0 == strcmp(input, "grade"))
        printf("%c\n", student.grade);
    else
        fprintf(stderr, "Command <%s> not recognized.\n", input);
}
Enter a command: score
42
  • Related