0
#include <stdio.h>
#include <stdlib.h>

struct fighter
{
    char *name, *category;
    int weight, age;
};

void enter_data(struct fighter *f, int n);
void display(struct fighter *f, int n);

int main(int argc, char const *argv[])
{
    int n;
    struct fighter *f;

    printf("Enter no. of fighter: "); scanf("%d",&n);

    f = (struct fighter *)malloc(n*sizeof(struct fighter));

    enter_data(f, n);
    display(f, n);
    return 0;


    for(int i=0; i<n; i++){
        free((f+i)->name);
        free((f+i)->category);
    }
    free(f);
}

void enter_data(struct fighter *f, int n){
    for(int i=0; i<n; i++){

        (f+i)->name=(char *)malloc(40*sizeof(char));
        (f+i)->category=(char *)malloc(40*sizeof(char));

        fflush(stdin);
        printf("Enter name of fighter: "); 
        scanf("%s[^\n]",(f+i)->name);
        //its not working full name, when I'm trying to give full name with space (ie. John Trump) its not working but when I'm giving only first name (ie. John) its working fine...

        fflush(stdin);
        printf("Enter age of fighter: ");  
        scanf("%d",&((f+i)->age));
        printf("Enter weight of fighter: ");  
        scanf("%d",&(f+i)->weight);
        printf("Enter category of fighter: "); 
        scanf("%s[^\n]",(f+i)->category);
    }
}

void display(struct fighter *f, int n){

    for(int i=0; i<n; i++){
        printf("\n\n");
        printf(" Name of fighter: "); 
        puts((f+i)->name);
        printf(" Age of fighter: ");  
        printf("%d \n",(f+i)->age);
        printf(" Weight of fighter: ");   
        printf("%d \n",(f+i)->weight);
        printf(" Category of fighter: "); 
        puts((f+i)->category);
    }
}

See in enter_data() function in there I have commented my issue...

When I'm giving full name with spaces its not taking rest of the inputs and directly jump to next iteration of loop. But when I'm giving first name or name with no spaces then its working fine.

This imgae is a output sceenshot when I'm giving full name.

This imgae is a output sceenshot when I'm giving first name only or name with no space.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • `"%s[^\n]"` You probably want `"%[^\n]"` instead. – dxiv Sep 09 '20 at 05:33
  • I would encourage you to consider [fgets()](https://linux.die.net/man/3/fgets). Nevertheless, if you're going to use scanf() ... and if you expected embedded strings ... then your syntax is incorrect. Here's one alternative: `scanf("%[^\n]%*c", str)`: https://www.geeksforgeeks.org/taking-string-input-space-c-3-different-methods – paulsm4 Sep 09 '20 at 05:35

1 Answers1

0

See How do you allow spaces to be entered using scanf?

Also, your return 0 should be after loops for freeing resources.

Quarra
  • 2,527
  • 1
  • 19
  • 27