#include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h> int main() { FILE* initialText; char** text; int i, countofstr; text = (char**) malloc(100 * sizeof(char*)); for (i = 0; i < 100; i++) { text [i] = (char*) malloc(100 * sizeof(char)); } initialText = fopen("Text.txt", "r"); countofstr = 0; /*ЦИКЛ для подсчета количества строк и записи строк в массив text[n][m]*/ for (i = 0; i < 100; i++) { fgets(text[i], 100, initialText); if (strcmp(text[i], "") == 0) { break; //если строка пустая, т.е. выход из цикла. } countofstr++; } printf("%d\n", countofstr); puts(text[0]); return 0; } 

There is a formatted text (Text.txt) in which the line does not have additional spaces between the lines. In the text itself can be no more than 100 lines and 100 characters per line. You must enter the text in the two-dimensional array text [n] [m] (n-address of the line; m - address of the character) and count the number of lines in the variable countofstr. For this, a for loop was written, but after its execution in the countofstr variable the wrong value.

Example:

Text.txt:
abcde
abcde
abcde

The result of the program:

18
abcde

  • Check the return value of fgets and use feof. because if it has nothing more to read, it returns NULL while the string itself remains unchanged (and anything after the malloc can be in the string, it is not filled with zeros). And text[i][0]==0 much more efficient check that the string is empty than strcmp - Mike

2 answers 2

What happens when the end of the file is reached? In the next text[i] nothing will be read, but the garbage that lies there will not allow the cycle to finish. Until 100 iterations pass or randomly in text[i] first character will not be the zero character ...

Check return fgets or null all text[i] . Although the idea itself, like this, in advance, to allocate an array of 100 by 100 personally does not appeal to me very much.

    Improve the loop, something like this.

     for(i = 0; i < 100; i++){ char * str = fgets(text[i], 100, initialText); if (str == NULL){ break; /*ошибка чтение или конец файла*/ } countofstr++; }