我是一个 C 菜鸟,我正在尝试编写一个程序来删除特定行。为此,我选择复制源文件的内容,跳过要删除的行。在我的原始代码中,我写道:
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
}
这给了我很多笑脸。
最后我找到了给出预期输出的代码:
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);
}
但这两个代码之间的实际区别是什么?
最佳答案
赋值的优先级低于不等于,所以:
read_char = fgetc(fp) != '\n'
导致read_char
得到一个0
或1
,比较fgetc()
的结果> 调用 '\n'
。
你需要括号:
while((read_char = fgetc(fp)) != '\n')
这会将 fgetc()
结果分配给 read_char
,然后再与 '\n'
进行比较。
关于删除一行的 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39260437/