我试图用数组结构打印一个字符串和一个整数,代码似乎很好,但在输出中不是1行值,而是在每个字符串后自动添加了新的一行。谁能帮帮我?
#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));
}
所需输出的例子:
Player A, 50 kg Player B, 60 kg
实际产出:
Player A,
50 kg
Player B,
60 kg
fgets
会在缓冲区中添加 nd(你按的'enter')。
你可以使用 strchr
以'/0'代替。
void scan(player *pscan){
...
*strchr(pscan->name, '\n') = '\0';
...
}
fgets
也会将换行符读入缓冲区,你需要删除它。
//...
fgets(pscan->name, 20, stdin);
pscan->name[strcspn(pscan->name, "\n")] = '\0';
//...
包括 string.h
.