【问题标题】:Logic error in loop循环中的逻辑错误
【发布时间】:2011-10-18 06:06:23
【问题描述】:

尝试向我的 struct Player 添加值,但操作后我的输出是垃圾:

输出如下:

名称:华纳 运行:0 未出局:0 怎么样:|||||||| (符号)

Player 是一个结构体:

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);
}

【问题讨论】:

  • 打印它的代码是什么样的?问题是“如何”输出还是其他问题?

标签: c file loops logic


【解决方案1】:

您永远不会在 player[i].how_out 中放置结束 '\0' - 您只需将 chars 放入其中。然后,您尝试将其打印为字符串。此时,printf 只会打印任何如果找到的内容,直到它达到随机 NULL,这就是你得到的垃圾。

要解决此问题,请确保 player[i].how_out 在最后一个字符后有一个 '\0'(或 NULL) - 并确保缓冲区足够大以容纳额外的 NULL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多