I would like to know how to replace all spaces in different sentences in a txt file with ellipses.
For example:
- Original sentence:
Hi my name is Joseph. - Modified sentence:
Hi... my... name... is... Joseph...
The text structure is the following:
- sentence 1.
- sentence 2.
- sentence 3.
- sentence 4.
- .......
(Each sentence ends with a dot). I have made a code but it only works from a manually typed sentence:
#include<stdio.h>
int main() {
char ch = getchar();
while (ch != EOF) {
if (ch != '\n' && ch != ' ') {
putchar(ch);
ch = getchar();
}
else {
printf("... ");
while (ch == '\n' || ch == ' ') {
ch = getchar();
}
}
}
putchar('\n');
return 0;
}
Does anyone know how to modify this code to read the sentences from the file and make the changes with the dots?
CodePudding user response:
Does anyone know how to modify this code to read the sentences from the file
Two ways:
- Use shell redirection, e.g.
./a.out < input.txt - Use
fopen,fgets,fclose. See man fopen.
CodePudding user response:
Wrong type
getchar() returns an int in the unsigned char range or the negative EOF. Those 257 different values can not be saved distinctively in a char. Use int or risk infinite loops or stopping too soon.
// char ch = getchar();
int ch = getchar();
To read/edit/write same file
Read from file1 (
fopen(... "r")), adjust" "into"...", write result to a new file2 opened with (fopen(... "w")).If successful,
rename()file1 into file_temp. Rename file2 to file1.If successful, delete file_temp.
The important thing is to not delete the data of old file until after the new file is successfully made and named - this aids in error recovery. Check the return values of the various FILE functions looking for errors.
