C语言读取TXT文件时首字符无法打印的问题求助
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 usesystem("clear")with conditional compilation.
内容的提问来源于stack exchange,提问作者Py11

