我正在尝试阅读n
,然后在n后面会有提示扫描数字和字符串,即“7 dwarf
”就像棒球名称一样,你知道“ 30 Rodriguez
“当然,正如您在我的代码中看到的那样,它会打印,然后提示另一次scanf,持续n次。
: -
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;
}
我的输出是......
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 . .
我正努力进入: -
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...
所以在{i} scanf
我的输入之后,所有同时出现在一个printf语句中的两个玩家的记录,这个printf将随着n的上升而扩展,在这种情况下它只有2,但是如果我投入5,它应该一次打印5个不同的玩家
答案 0 :(得分:1)
您可以根据输入malloc
n
动态创建数组。
#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;
}