简体   繁体   中英

Commands in an if statement in C occurring whether or not the statement is true

For a program I'm writing I need to read a file line by line and print out the longest line in the file, along with the length of that line as well as the total number of lines in the file.

I have this:

char line[100];
char* longLine;
int count, longestLine, temp;

count=0;
longestLine=0;

while(fgets(line,100,inFile) != NULL) {
    temp=strlen(line);  
    if(temp > longestLine) {            
        longLine=line;
        longestLine=temp;
    }
    count++;
}
printf("Longest line: %sLength of longest line: %d characters\nTotal number of lines: %d\n",longLine, longestLine, count);

longestLine and count print correctly, but no matter what, longLine always prints out the last line of the file instead of the longest line. Using print statements I've determined that the if statement in the while loop is only called when a new longest line is found, yet longLine gets changed regardless. Can anyone tell me what I'm doing wrong? Thanks!

The problem is that longLine is a pointer. You're going into the if and then setting longLine to point to line... which at the start of the next while has changed. What I suspect you intended to do was copy the contents of line into longLine using strcpy, otherwise, each time through the loop. longLine will always point to the currently evaluating line.

A footnote, your code is incorrect even if the code function correctly. You need to initialize longestLine to zero before it is used. Not all compilers may initialize it to zero - it might have garbage in it. Temp may never be larger than the garbage in longestLine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM