0

I was trying to print a string and an integer using array of structs and code seems to be fine, but in the output instead of 1 line of values, after each string a new line is automatically added. Can someone please help?

#include <stdio.h>

typedef
    struct player_main{
        char name[20];
        int total;
    }
player;

void print(player pprint);
void scan(player *pscan);

int main(){
    player user[2];
    for(int i = 0; i < 2; i++){// scanned
        printf("Player %d", i+1);
        scan(&(user[i]));
    }
    for(int i = 0; i < 2; i++){// printed
        print(user[i]);
    }

    return 0;
}
void print(player pprint){
    printf("%s Weight:%d kg\n", pprint.name, pprint.total);

}
void scan(player *pscan){
    printf("\nName: \n");
    fgets(pscan->name, 20, stdin);
    printf("\nEnter weight:");
    scanf("%d%*c", &(pscan->total));

} 

Example of desired output:

Player A, 50 kg    Player B, 60 kg

Actual output:

Player A,
50 kg
Player B,
60 kg
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39

2 Answers2

1

fgets adds \n (the 'enter' you press) to the buffer.

You can use strchr to replace it with '\0';

void scan(player *pscan){
    ...
    *strchr(pscan->name, '\n') = '\0';
    ...
}
MrBens
  • 1,227
  • 1
  • 9
  • 19
1

fgets also reads the newline character into the buffer, you will need to remove it:

//...
fgets(pscan->name, 20, stdin);
pscan->name[strcspn(pscan->name, "\n")] = '\0';
//...

Include string.h.

Running code

anastaciu
  • 23,467
  • 7
  • 28
  • 53