I have this exrcise. I need to read from a file a text and copy this text to a second file but I need to remove adjacent duplicate characters, for example
"aabbcc" --> "abc".
that's the basic idea.
this is my solution,
#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;
}
but the problem is that the output is this:
"e,wrd ewrdÿ".
the input text was: "hello, world! heyyyyyyyyyyyy worlllllddddddd".
I've used the usual loop for reading something in C, (1) read (2) check (3) use, I've read the first character (stored in c), I've checked if it's not EOF, and after that, I've read the next character (stored in d).
CodePudding user response:
You need to read one character at a time and remember the last one you read.
It could look like this:
// ...
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
}
}
// ...