当前位置: 动力学知识库 > 问答 > 编程问答 >

string - C: Reading from a file is bugged

问题描述:

This question is an exact duplicate of:

  • C file handling query

    1 answer

网友答案:

I guess your file is not terminated by a newline. So the last word, Pig, gets truncated by this line of code:

str[strlen(str)-1] = '\0';

(which is unconditional).

Either put a newline at the end of your file, or check the end-of-string before truncating:

if (isspace(str[strlen(str)-1]))
    str[strlen(str)-1] = '\0';

(Might also use strtok to remove all whitespace from the string without writing tricky code)

网友答案:

You need to check if the last character is a linefeed in both the user input and the line read from the file, and remove it if and only if it is. (You also need to fix the other bugs, such as the use of gets and feof, and not all the changes can be done in isolation because some of your bugs depend on one another so fixing only one will break it until you fix the others.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: