簡體   English   中英

為什么下面C代碼的output中有多余的字符?

[英]Why are there extra characters in the output of the following C code?

我有文件statistics.txt以下數據在哪里:

Mark = 100
Andy = 200

然后,我寫了這段代碼:

FILE *file_statistics_reading = fopen("statistics.txt", "r");

char line[1024];
int n = 0;
char player[10];

while (fgets(line, sizeof(line), file_statistics_reading) != NULL) {
    n = 0;
    for (int i = 0; i < 10; i++) {
        if ((line[i] > 'A') && (line[i] < 'z')) {
            player[n] = line[i];
            n = n + 1;
        }
    }
    printf("%s", player);
}

fclose(file_statistics_reading);

我想從文本文件中提取球員的名字並打印出來,但是 output 看起來像這樣:

Mark╠╠╠╠╠╠╠╠╠╠╠╠╠
Andy╠╠╠╠╠╠╠╠╠╠╠╠╠

有什么解決辦法嗎?

代碼中存在多個問題:

  • 您忘記在player中的名稱后設置 null 終止符,這解釋了 output 中的隨機字節。 player是一個自動數組:它的內容在創建時是不確定的。
  • 你應該讓player長一個字節。
  • 字母測試不正確: 'A''z'將導致循環停止,因為您使用><而不是>=<=
  • 根據字符集,將打印一些非字母字節,例如[\]^_`用於 ASCII。 您應該使用<ctype.h>中的isalpha()
  • 如果行中出現多個單詞,則前 10 個字節中的字母作為所有行的單個 blob。 用換行符分隔 output。
  • 您不檢查行尾,因此即使讀取超出行尾的內容也會測試 10 個字節,其內容是不確定的。

這是修改后的版本:

#include <ctype.h>
#include <stdio.h>

void print_players(void) {
    char line[1024];
    FILE *file_statistics_reading = fopen("statistics.txt", "r");
    
    if (file_statistics_reading == NULL) {
        perror("cannot open statistics.txt");
        return;
    }
    while (fgets(line, sizeof(line), file_statistics_reading) != NULL) {
        char player[11];
        size_t n = 0;
        for (size_t i = 0; n < sizeof(player) - 1 && line[i] != '\0'; i++) {
            if (isalpha((unsigned char)line[i]) {
                player[n++] = line[i];
            }
        }
        player[n] = '\0';
        printf("%s\n", player);
    }
    fclose(file_statistics_reading);
}

這是打印行中第一個單詞的另一種方法:

#include <stdio.h>
#include <string.h>

void print_players(void) {
    char line[1024];
    FILE *file_statistics_reading = fopen("statistics.txt", "r");
    const char *letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    if (file_statistics_reading == NULL) {
        perror("cannot open statistics.txt");
        return;
    }
    while (fgets(line, sizeof(line), file_statistics_reading) != NULL) {
        int start = strcspn(line, letters);       // skip non letters
        int len = strspn(line + start, letters);  // count letters in word
        printf("%.*s\n", len, line + start);
    }
    fclose(file_statistics_reading);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM