My program requires to get input from a textfile and output it on a single line.
However if the amount of characters on a singular line exceed 60, there should be a new line.
The code I have so far:
int main(int argc, char *argv[]){
FILE *pFile;
char x[10];
char *token;
pFile = fopen("test5.txt","r");
int wordLength;
int totalCharLength;
char newline[10] = "newline";
if(pFile != NULL){
while (fgets(x, sizeof(x), pFile) != NULL) {
token = strtok(x,"\r\n");
if(token != NULL){
printf("%s",x);
}
else{
printf("%s",x);
}
//counter++;
wordLength = strlen(x);
totalCharLength += wordLength;
printf("%d",totalCharLength);
if(totalCharLength == 60){
printf("%s",newline);
}
}
fclose(pFile);
}
}
Textfile:
a dog chased
a cat up the
tree. The cat
looked at the dog from
the top of the tree.
There are 5 separate lines. Which displays this. This is not all on one line.
Output:
a dog chased a cat up the tree. The cat looked at the dog from the top of the tree.
Now the program needs to be able to get input text in that format and print out in a single line.
So the above Output there should be a new line at the 60th char which is before second word "dog".
However I want to add a feature so that there is a counter for character and it prints a new line when character count = 60.
Now with some more debugging I added the code
printf("%d",totalCharLength);
just before the if(totalCharLength==60) line and I realize that the characters get counted in random increments instead of one by one. Output:
a dog cha9sed 13a cat up 22the 26tree. The35 cat 40looked at49 the dog 58 from 63 the top o72f the tre81e. 85
So this shows that it does not count character by character. However when I change charx[10] to a lower value it does not print everything on one line. It will leave gaps.
Example: Changing charx[10] to charx[2]
This correctly gets character by character however the output is not in on one line.
The only time there should be a new line is when characters exceed 60 in a line. Not 14 (First line).
a2 3d4o5g6 7c8h9a10s11e12d13 14
30a17 18c19a20t21 22u23p24 25t26h27e28 29
46t32r33e34e35.36 37T38h39e40 41c42a43t44 45
71l48o49o50k51e52d53 54a55t56 57t58h59e60newline 61d62o63g64 65f66r67o68m69 70
72t73h74e75 76t77o78p79 80o81f82 83t84h85e86 87t88r89e90e91.92 93 94
I think you are best just printing each char on his own, and check for a space before adding the newline.
Something like:
((charCount > 60) && (currentChar == ' ')) {
// print newline and reset counter
printf("\n");
charCount = 0;
}
Edit:
before anything check if the current char is a newline already and skip it.
Check the carriage return \r
as well since in windows newlines are \r\n
.
#include <stdio.h>
int main(void) {
FILE *f = fopen("test.txt", "r");
if(!f) {
printf("File not found.\n");
return 1;
}
char c;
int cCount = 0;
while((c = fgetc(f)) != EOF) {
if(c == '\r') continue;
if(c == '\n') c = ' ';
printf("%c", c);
if((cCount++ > 60) && (c == ' ')) {
printf("\n");
cCount = 0;
}
}
fclose(f);
return 0;
}