How to print a string in C?

Asked

Viewed 985 times

0

I’m studying C and I want to make an algorithm that reads the names of 30 students in a class and returns the highest grade, lowest grade and the names of these students. I have already researched a lot and still can’t put the name of the students with the highest and lowest grade. My code so far is like this (with error):

#include<stdio.h>

main(){
char aluno[21],Maluno[21], maluno[21];
float nota, maiorNota=0, menorNota=10;
int i;

for(i=0; i<30; i++){
printf("Insira o nome do(a) aluno(a) %d:\n", i+1);
fflush(stdin);
scanf("%s", aluno);

printf("Insira a nota do(a) aluno(a) %s:\n", aluno);
fflush(stdin);
scanf("%f", & nota);

if(nota>=0 && nota <=10){

if(maiorNota<nota){
    maiorNota = nota;
    Maluno = aluno;
}

if(menorNota>nota){
    menorNota = nota;
    maluno = aluno;
}
}
}
printf("Aluno com a menor nota e o: %s\n que tirou%f\n" ,maluno,menorNota );
printf("Aluno com a maior nota e o: %s\n que tirou%f\n" ,Maluno,maiorNota );
}

Someone would know how to do that?

1 answer

1


In the case of string you can’t go from one variable to another like this:

maluno = aluno;

You need the function strcpy library <string.h>.

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

int main()
{
    char aluno[21], Maluno[21], maluno[21];
    float nota, maiorNota = 0, menorNota = 10;
    int i;

    for (i = 0; i < 30; i++)
    {

        printf("Insira o nome do(a) aluno(a) %d:\n", i + 1);
        fflush(stdin);
        scanf("%20s", aluno);

        printf("Insira a nota do(a) aluno(a) %s:\n", aluno);
        fflush(stdin);
        scanf("%f", &nota);

        if (nota >= 0 && nota <= 10)
        {

            if (maiorNota < nota)
            {
                maiorNota = nota;
                strcpy(Maluno, aluno);
            }

            if (menorNota > nota)
            {
                menorNota = nota;
                strcpy(maluno, aluno);
            }
        }
    }
    printf("Aluno com a menor nota e o: %s\n que tirou %f\n", maluno, menorNota);
    printf("Aluno com a maior nota e o: %s\n que tirou %f\n", Maluno, maiorNota);

    return 0;
}

For more information about the function you can take a look here

  • I used this string library function but it keeps going wrong. I have no idea what I’m doing wrong

  • if(highest case<note){ highest case = note; strcpy(highest case,student); } if(lowest case>note){ bottom strcpy(menoraluno,);

  • @Jackgba adjusted the answer, had forgotten the part of the delimiter character

  • 1

    The scanf()already puts the '\0' in the string. It is not necessary to do so before, but it is convenient to limit the scanf to avoid buffer overflow: scanf("%20s", aluno);

Browser other questions tagged

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