简体   繁体   English

为什么下面C代码的output中有多余的字符?

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

I have file statistics.txt where is the following data:我有文件statistics.txt以下数据在哪里:

Mark = 100
Andy = 200

Then, I wrote this code:然后,我写了这段代码:

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);

I want to extract the names of the players from the text file and print them out, but the output looks like this:我想从文本文件中提取球员的名字并打印出来,但是 output 看起来像这样:

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

Any solutions?有什么解决办法吗?

There are multiple problems in the code:代码中存在多个问题:

  • You forgot to set a null terminator after the name in player , which explains the random bytes in the output.您忘记在player中的名称后设置 null 终止符,这解释了 output 中的随机字节。 player is an automatic array: its contents are indeterminate at creation time. player是一个自动数组:它的内容在创建时是不确定的。
  • You should make player one byte longer.你应该让player长一个字节。
  • The test for letters is incorrect: 'A' and 'z' will cause the loop to stop because you use > and < instead of >= and <=字母测试不正确: 'A''z'将导致循环停止,因为您使用><而不是>=<=
  • Depending on the character set, some non letter bytes will get printed, such as [ , \ , ] , ^ , _ and ` for ASCII.根据字符集,将打印一些非字母字节,例如[\]^_`用于 ASCII。 You should use isalpha() from <ctype.h> .您应该使用<ctype.h>中的isalpha()
  • If multiple words appear in the line, the letters in the first 10 bytes, as a single blob for all lines.如果行中出现多个单词,则前 10 个字节中的字母作为所有行的单个 blob。 Separate the output with newlines.用换行符分隔 output。
  • You do not check for the end of line, so 10 bytes are tested even by reading beyond the end of line, whose contents are indeterminate.您不检查行尾,因此即使读取超出行尾的内容也会测试 10 个字节,其内容是不确定的。

Here is a modified version:这是修改后的版本:

#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);
}

Here is an alternative approach to print the first word from the line:这是打印行中第一个单词的另一种方法:

#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