1

I am a beginner in C. I am making a simple game in c. I have a .txt file that stores players' score such as

gse
12
CKY 
8
asf
8
FWD
7
BCS
6
BBC
5
PYS
4
NSE
3
Jaeh
2
PJH
1

and the one of the functions in my c code is the following:

void ViewScoreBoard() { 
int n = 0;
int c;
char buffer[NAME_LENGTH] = { 0 };
FILE *fp = fopen("scoreBoard.txt", "r");

if (fp == NULL) {
    printf("no score\n");
    fflush(stdin);
    getchar();
    return;
}

system("cls");//clears the screen

printf("=======SCORE=======\n");
if (fp){
   while(fgets(buffer, sizeof buffer, fp)!=NULL){
        if(n%2==0){
            printf("%2d. ",n/2+1); //index
            buffer[strcspn(buffer, "\n")] = 0; //stripes the newline chr
            printf("%5s",buffer);            
        }
        if(n%2==1){
            printf("%5s",buffer);
        }
        n++;
    }

    fclose(fp);
}

printf("Enter AnyKeys");
Sleep(100);
getchar();
getchar();}

The problem is this. On the console, the score is printed out fine up until 3.(before Jaeh)

=======SCORE=======
 1.   gse  12
 2.   CKY   8
 3.   asf   8
 4.   FWD   7
 5.   BCS   6
 6.   BBC   5
 7.   PYS   4
 8.   NSE   3
 9.  Jaeh
10.     2 PJH
11.     1Enter AnyKeys

I need 2 to be inline with Jaeh but don't know what's wrong... Thanks in advance!

***EDIT

changed the code to char buffer[NAME_LENGTH+2] = { 0 }; and everything works fine.

Thanks everyone!

Py11
  • 129
  • 1
  • 2
  • 7

0 Answers0