Problem printing code involving strings (c language)

Asked

Viewed 31 times

0

#include <stdio.h>

#define DIAS 7

typedef struct {
   char nome[51];
   int idade;
   int refrigerante[7];
}Paciente;

int main() {   

   Paciente habitos;
   //Lendo os dados do paciente
   fgets(habitos.nome,51,stdin);
   scanf("%d", &habitos.idade);
   for (int i = 0; i < DIAS; i++) {
     scanf("%d", &habitos.refrigerante[i]);
   }
int k; //constante
scanf("%d", &k);

int x = 0;

for (int i = 0; i < DIAS; i++) {
    if (habitos.refrigerante[i] > k) {
        x++;
    }
}

   printf("%s toma mais que %d refrigerantes %d vezes por semana", habitos.nome, k, x);

return 0;
}

I would like the code to be printed on a single line. However, after executing the string, the code jumps a line and prints the rest of the text. Where is the error?

  • 2

    fgets() will read the '\n' of the string, unless it has exact 51 bytes in the input. Test the last byte and if it is '\n' change to zero. Post an entire program here, compileable, INSIDE the code box :) ALWAYS TEST the return of scanf(). What is the purpose of following the loop if you could not read the age, for example?

1 answer

1

does this right after calling the fgets:

if(habitos.nome[strlen(habitos.nome)-1] == '\n')
    habitos.nome[strlen(habitos.nome)-1] = 0;

fgets adds newline Character to the end of the string, so you need to remove it.

Browser other questions tagged

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