尝试将值添加到我的struct Player中,但操作后我的输出是垃圾:
输出如下:
Name: Warner runs: 0 not out: 0 how out: |||||||| (symbols)
播放器是一个结构:
Player {
int not_out, innings, runs;
char pname[MAX_NAME];
char how_out[5];
}
这是我的代码:
void scan_stats (Team_t player[]) {
int i, status, runs, turns;
char out;
char string[MAX_PLYR];
FILE *inp;
inp = fopen("teamstats.txt", "r");
do
{
fscanf(inp, "%s" "%d" "%*c" "%c", &string, &runs, &out);
printf("%s %d %c\n", string, runs, out); /*They scan perfectly*/
for (i = 0; i < MAX_PLYR; i++) {
player[i].innings = 0;
player[i].runs = 0;
player[i].not_out = 0;
turns = -1;
if (status = (strcmp(player[i].pname, string)) == 0) {
player[i].innings = player[i].innings + 1;
player[i].runs = player[i].runs + runs;
turns = turns + 1;
if (out == 'n') {
player[i].not_out = player[i].not_out + 1;
}
else {
player[i].how_out[turns] = out;
}
}
}
} while (!feof(inp)); /*Printing the values of player at the end of this loop
produces garbage/ incorrectness*/
fclose(inp);
}
答案 0 :(得分:0)
您永远不会在播放器[i] .how_out中放置结束'\0'
- 您只需将char
放入其中。然后,您尝试将其打印为字符串。此时,printf
只会打印出任何内容,直到找到随机的NULL,这就是你得到的垃圾。
要解决此问题,请确保播放器[i] .how_out在最后一个字符后面有一个'\ 0'(或NULL
- 并确保缓冲区足够大以容纳该额外的NULL。