[英]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()
。這是修改后的版本:
#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.