Receive an integer and a string and store it in 2 vectors in C? [closed]

0

I'm learning C and I'm stuck in an exercise that asks you to store the data as follows.

Student Note and Student Name on the same line, and then with a chosen index determine the situation of the student, the part of manipulating the index and checking the grade of it I know how to do, but I am having problems in what it would be like doing this type of problem using vectors in C that receive an integer and a string that passes to 2 vectors.

Data example:

8.0 Ed Rex
9.0 Marcos Vice 
1.0 Alan Pequenuxo

This would be my code

include stdio.h
include stdlib.h
include string.h

int main()
{
    int n,i;
    int nota[99];
    char aluno[20][30];
    scanf("%d",&n);

    for (i=0 ;i < n; i++){
        scanf("%d %s",&nota[i], &aluno[i]);
    }

    return 0;
}
    
asked by anonymous 17.09.2017 / 16:56

1 answer

1

I think the most correct way to solve your problem is to aggregate what is common in a structure. Thus, the note and name belong to the Student structure. So your program would look like this:

#include <stdio.h>

typedef struct Aluno
{
    float nota;
    char nome[100];
} Aluno;

int main()
{
    int n = 0, i = 0;
    Aluno aluno[30];
    scanf("%d",&n);

    for (i = 0; i < n; i++){
        scanf("%f %100[0-9a-zA-Z ]",&aluno[i].nota, aluno[i].nome);
    }

    for (i = 0; i < n; i++) {
        printf("%f %s\n", aluno[i].nota, aluno[i].nome);
    }

    return 0;
}

Note no% with a strange directive: scanf . It looks like a regex and allows you to format exactly what you want as input to the %100[0-9a-zA-Z ] field. In other words, it will accept a maximum of 100 characters, where they can be 0-9, a-z, A-Z and / or white space.

If you want to use accented characters, you can also replace it with: aluno[i].nome . That is, it reads anything until the end of the line

    
18.09.2017 / 03:59