According to the assignment, it was necessary to process the text so that each sentence began with a capital letter and there were no words with gaps in the output to the console. The result was required to display in a file and on the console. Text processing, like, I did. But when outputting an array of processed text, extra characters appear in the file. Apparently, memory is incorrectly allocated?

On case 2: I ask you not to pay attention, there should be a search for words in the text, but I haven’t got to that yet.

Full code:

 #include <stdio.h> #include <malloc.h> #include <stdlib.h> unsigned search (FILE* file, char *x); void correction (char *x, unsigned size, unsigned max); int main() { FILE *myfile; char *text; unsigned k, size, max; system("chcp 1251"); system("cls"); printf("Выберите необходимое действие: \n 1) Обработка текста; \n 2) Поиск слова в тексте. \n"); scanf("%d", &k); switch (k) { case 1: myfile = fopen ("input.txt", "r"); fseek(myfile, 0, SEEK_END); size = ftell(myfile); rewind(myfile); text=(char*) malloc(size); max=search(myfile, text); fclose(myfile); myfile = fopen ("output.txt", "w"); correction(text, size, max); fprintf(myfile, "%s", text); fclose(myfile); free(text); break; case 2: myfile = fopen ("output.txt", "r"); } return 0; } unsigned search (FILE* file, char *x) { unsigned i=0, k=0, max=0; while ((x[i] = fgetc(file)) != EOF) { if ((x[i] != ' ') && (x[i] != '\n')) ++k; else k=0; if (k>max) max=k; ++i; } return max; } void correction (char *x, unsigned size, unsigned max) { unsigned k=0, i=0; if ((x[i]<123) && (x[i]>96)) printf("%c", x[0]=x[0]-32); else printf("%c", x[0]); for (i=1; i<(size-2); ++i) { ++k; if (x[i-2]=='.' && ((x[i-1]==' ') || (x[i-1]=='\n')) && (x[i]<123) && (x[i]>96)) printf("%c", x[i]=x[i]-32); else if ((x[i]==' ') && (k>(120-max))) { printf("\n"); k=0; } else printf("%c", x[i]); } } 

    1 answer 1

    Memory is allocated correctly. Just for processing, you use strings of a given length, and when outputting to the fprintf function file (% s), you need an ASCII-z string. And since you have a string of a given length (max), then it will not be equal to ASCII-z (the program displays the correct ASCII-z value in terms of this concept, that is, your value + piece of garbage from memory to the first zero). Then if you want to use fprintf - then 1) or do a cycle and output it by the symbol 2) or add +1 byte to the memory, do not transfer this byte to the memory in correction, fill it with zero that would be ASCII-z - and you will have happiness.

    As the simplest example [1], you need fprintf (myfile, "% s", text); replaced by

     for(k=0;k<max;k++) fprintf(myfile, "%c", text[k]); 

    or better

     fwrite(text,1,max,myfile);