-1

I'm trying to read in n, and on n subsequent there will be a prompt to scan in a number and a string, i.e. "7 dwarf" just like baseball names, you know "30 Rodriguez" however of course as you can see within my code, it will print, and then prompt another scanf, for n number of times. :-

int main (void) {



int n, number, i;
char word[1000];

scanf("%d", &n);

for (i=0; i<n; i++) {
    scanf("%d %s", &number, &word);

    printf("Player %d's record: %s\n", number, word);
    printf("Player %d's batting average is\n", number);
}   


system("pause");
return 0;

}

my output is...

2
12 harambe
Player 12's record: harambe
Player 12's batting average is
13 Muhammad
Player 13's record: Muhammad
Player 13's batting average is
Press any key to continue . . 

I'm trying to make it into:-

2
12 harambe
13 Muhammad

player 12's record: harambe
player 12's batting average is

player 13's record: Muhammad
player 13's batting average is
press any key to continue...

so AFTER i scanf my inputs, all at once BOTH player's records are brought up in one printf statement, this printf will scale with how high n goes up to, in this situation it's only 2, but if i put in 5, it should print 5 different players at once .

Uiop737
  • 7
  • 4

1 Answers1

1

You can creates an array dynamically by malloc according to the input n.

like this

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

typedef struct player {
    int number;
    char name[64];
} Player;

int main(void){
    int n;

    scanf("%d", &n);
    Player *recs = malloc(n * sizeof(Player));
    if(recs == NULL){
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    for(int i = 0; i < n; i++) {
        if(2 != scanf("%d %63[^\n]%*c", &recs[i].number, recs[i].name)){
            printf("invalid input.\ninput again!\n");
            while(getchar() != '\n'); //clear input
            --i;
        }
    }
    puts("");
    for(int i = 0; i < n; i++) {
        printf("Player %d's record: %s\n", recs[i].number, recs[i].name);
        printf("Player %d's batting average is \n", recs[i].number);
    }
    free(recs);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70