C file handling query

后端 未结 1 1894
灰色年华
灰色年华 2020-12-12 06:05

So I have a program that takes user input and compares it to a specific line in a file, however the final line will always be credited as incorrect, so can someone solve thi

相关标签:
1条回答
  • 2020-12-12 06:43

    Some observations:

    You must never use gets (it is not even in the C11 standard anymore). Instead of gets(text) use fgets(text, sizeof(text), stdin) – this way a long input will not overflow the text array.

    There will be stuff printed at the end because you don't check the return value of either the gets or the fgets, so when end of file occurs for either the file or for user input the rest of that iteration still runs. fgets returns NULL if it didn't read anything – check for that instead of using feof.

    You remove newlines from the file input but not from the user input, so the comparison will always fail when you switch from gets to fgets (which doesn't strip linefeeds). The second (otherwise pointless) comparison of text[c] against ' ' should be against '\n'.

    edit: Also, in case the last line of your file does not end in a linefeed, the comparison will fail on the last line because you don't check if the last character is a linefeed before you remove it.

    The for (loop = 0; loop < line; ++loop) -loop is pointless because line is always 1, so the body is only executed once.

    You have unnecessarily global variables which the program hard to follow. And, for instance, your local text[64] overshadows the global text[100], so if you think you are modifying the global buffer, you are not. If your code is complete, none of the variables should be global.

    The function getch() is non-standard. There is no easy direct replacement, so you may just accept that you are not writing portable code, but it's something to be aware of.

    0 讨论(0)
提交回复
热议问题