Take an integer and a string and store in 2 vectors in C?

Asked

Viewed 106 times

0

I am learning C and am locked in an exercise that asks to store the data as follows.

Student’s Grade and Student’s Name on the same line, and then with a chosen index determine the student’s status, the part of manipulating the index and checking his grade I know how to do, but I’m having problems with what it would be like to do this kind 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

That 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;
}
  • 2

    And what a problem you’re having?

  • This error appears when I try to compile. names. c: In Function ?main': names. c:12:10: Warning: format%s' expects argument of type ːchar ', but argument 3 has type ľchar ()[30]' [-Wformat=] scanf("%d %s",&note[i], &student[i]); ^

  • Exchange: &student[i] per student[i] in the scanf (take the &).

  • thanks friend, I can’t believe it was just because of that. but if I wanted him to keep his surname, what could I do?

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 the 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 on scanf a strange directive: %100[0-9a-zA-Z ]. It looks like a regex and allows you to format exactly what you want as input to the field aluno[i].nome. In other words, it will accept a maximum amount 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: %100[^\n]. I mean, read anything to the end of the line

  • The only thing I disliked was wearing a struct for the scenario where the AP is still learning the basics. Of all sorts +1

  • I’m really learning, but this part of the struct can help me for future problems that need this reasoning.Thanks for the help as well

Browser other questions tagged

You are not signed in. Login or sign up in order to post.