I am a C noob, and I was trying to make a program to delete a specific line. For this, I chose to copy the contents of the source file, skipping the line intended for deletion. In my original code, I wrote:
while(read_char = fgetc(fp) != '\n') //code to move the cursor position to end of line
{
printf("%c",read_char); //temporary code to see the skipped characters
}
which gave me lots of smileys.
In the end I found the code which gave the intended output:
read_char=fgetc(fp);
while(read_char != '\n') //code to move the cursor position to end of line
{
printf("%c",read_char); //temporary code to see the skipped characters
read_char=fgetc(fp);
}
But what is the actual difference between these two codes?
Assignment has lower priority than not-equal, so:
read_char = fgetc(fp) != '\n'
results in read_char
getting a 0
or 1
, the result of comparing the result of the fgetc()
call against '\\n'
.
You need parentheses:
while((read_char = fgetc(fp)) != '\n')
which will assign the fgetc()
result to read_char
before comparing with '\\n'
.
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.