Я использую этот код внутри функции, чтобы получить самую короткую и самую длинную строку в файле. Переменные длины и строки объявляются вне цикла. Переменные int
корректно обновляются внутри и снаружи цикла, но переменные char*
корректно обновляются только внутри.
в последнем утверждении printf, которое я получаю:
the string Zulia
is the longest in a2.txt and has 18 chars
the string Zulia
is the shortest in a2.txt and has 5 chars
Что здесь происходит?
fp1 = fopen(fileName, "r");
if (fp1 == NULL)
{
printf("Error while opening file: %s\n",fileName);
exit (1);
}
int lengthLongestString=1;
int lengthShortestString=1000;
int lengthActualString=0;
char *longestString;
char *shortestString;
char *currentString;
while (fgets(fileLine, SIZE_OF_LINE, fp1) != NULL)
{
if(((strcmp(fileLine, "\n") != 0)) && (strcmp(fileLine, "\r\n") != 0)){ //Validates against storing empty lines
lineas[numeroLineas++] = strdup(fileLine);
lengthActualString=strlen(fileLine);
currentString=fileLine;
if (lengthActualString>lengthLongestString){
lengthLongestString = lengthActualString;
longestString=fileLine;
printf("the longest string now is %s \n",longestString);
}
else if (lengthActualString<lengthShortestString){
lengthShortestString = lengthActualString;
shortestString=fileLine;
printf("the shortest string now is %s \n",shortestString);
} // END IF
}// END IF
} //END WHILE
printf("the string %s is the longest in %s and has %d chars\n",longestString, fileName, lengthLongestString );
printf("the string %s is the shortest in %s and has %d chars\n",shortestString, fileName, lengthShortestString);