You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言读取TXT文件时首字符无法打印的问题求助

Fix for Missing First Character When Reading Your Score File in C

Hey there! Let's break down why your first character isn't showing up—it's a classic operator priority gotcha that trips up a lot of new C devs.

The Core Issue

Look at this line in your code:

while((c=getc(fp)!=EOF))

The problem is operator precedence: != has higher priority than =. So this line is actually being interpreted as:

c = (getc(fp) != EOF)

Instead of storing the actual character you read from the file into c, you're storing a boolean value (0 or 1) that tells you if the character was not EOF. That first character gets read by getc() but never saved to c—so it's lost entirely.

Quick Fix

Just adjust the parentheses to group the assignment first:

while( (c = getc(fp)) != EOF ) {
    // Your existing character-processing logic here
}

This way, you first read the character into c, then check if it's not EOF.

A Better Approach for Your Use Case

Since your score file uses space-separated values (like gse 12 CKY 8), you don't need to read characters one by one. Using fscanf will make your code cleaner and less error-prone:

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

#define NAME_LENGTH 20

void readScoreBoard() {
    char name[NAME_LENGTH] = {0};
    int score;
    FILE *fp = fopen("scoreBoard.txt", "r");

    if (fp == NULL) {
        printf("no score available\n");
        // Replace fflush(stdin) — it's undefined behavior!
        int ch;
        while ((ch = getchar()) != '\n' && ch != EOF);
        getchar();
        return;
    }

    system("cls"); // Note: This only works on Windows; use platform-specific logic for cross-platform code

    // Read name-score pairs directly
    while (fscanf(fp, "%s %d", name, &score) == 2) {
        printf("Player: %s | Score: %d\n", name, score);
    }

    fclose(fp); // Don't forget to close the file! Your original code missed this
}

Extra Tips to Avoid Future Headaches

  • Always close files with fclose(fp) when you're done—leaving them open wastes system resources.
  • fflush(stdin) is undefined behavior in C (it only works reliably for output streams). Use a loop to clear the input buffer instead, like in the code above.
  • system("cls") is Windows-only. If you want your code to work on Linux/macOS, you can use system("clear") with conditional compilation.

内容的提问来源于stack exchange,提问作者Py11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:17:46