我有這個練習。我需要從檔案中讀取文本并將此文本復制到第二個檔案,但我需要洗掉相鄰的重復字符,例如
"aabbcc" --> "abc".
這是基本的想法。
這是我的解決方案,
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int remove_doubles(const char* filein, const char* fileout) {
if (!filein || !fileout) {
return 0;
}
FILE* f = fopen(filein, "r");
if (f == NULL) {
return 0;
}
FILE* g = fopen(fileout, "w");
if (g == NULL) {
return 0;
}
while (1) {
int c = fgetc(f);
if (c == EOF) {
break;
}
int d = fgetc(f);
if (c != d) {
fprintf(g, "%c", d);
}
}
fclose(f);
fclose(g);
return 1;
}
int main(void) {
char filein[] = "test.txt";
char fileout[] = "out_test.txt";
int c = remove_doubles(filein, fileout);
return 0;
}
但問題是輸出是這樣的:
"e,wrd ewrd?".
the input text was: "hello, world! heyyyyyyyyyyyy worlllllddddddd".
我已經使用通常的回圈來讀取 C 中的內容,(1)讀取(2)檢查(3)使用,我已經讀取了第一個字符(存盤在 c 中),我已經檢查了它是否不是 EOF,然后那,我讀過下一個字符(存盤在d中)。
uj5u.com熱心網友回復:
您需要一次閱讀一個字符并記住您閱讀的最后一個字符。
它可能看起來像這樣:
// ...
int c, d = EOF; // init `d` to some "non"-character
while ((c = fgetc(f)) != EOF) {
if (c != d) { // not same as the previous?
fputc(c, g); // ok, print it
d = c; // and assign c to d
}
}
// ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505053.html
