How to stimulate EOF without preceding newline in C

情到浓时终转凉″ 提交于 2019-12-01 12:14:42

Converting my comment into an answer:

On which platform? On Unix and derivatives, you would type the EOF 'character' twice — usually control-D rather than control-Z, though. That may also work on Windows; I don't know, but it is worth a try.

(A response comment affirms that the platform is Windows.)

On Unix, control-D makes the data on the line available to the program. The first control-D gives it what you've typed already; the second gives it zero bytes to read, which is the indication of EOF.

Then avoid storing the newline, in the loop. It's not as if you're being forced to store all characters regardless of value. :)

Also, you're not terminating the string correctly. This:

line[i++] = c;

should be:

line[i] = '\0';

And of course, it's sensitive to buffer overflow.

In general, you'd be better of using fgets().

EDIT: I might be missing the point, but it seems to be that the entire focus on EOF is ... misguided, if all you want to do is read a line. Lines are not generally terminated with EOF, but with \n. So the function should probably just store characters until either EOF or \n is encountered.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!