2011-10-18 78 views
0

試圖將值添加到我的結構的球員,但我的輸出爲他們手術後是垃圾:邏輯錯誤

輸出的樣子:

 
    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

打印它的代碼是什麼樣的?問題是「如何輸出」或其他什麼? – user995048

回答

0

你永遠不會在player [i] .how_out中放置一個關閉'\0' - 你只需在其中放置char即可。然後,您嘗試將其打印爲字符串。在這一點上,printf只是發現什麼,如果發現,直到它得到一個隨機NULL,這就是你得到的垃圾。

要解決這個問題,請確保player [i] .how_out在最後一個字符後有一個'\ 0'(或NULL) - 並確保緩衝區足夠大,以滿足額外的NULL。