How to stimulate EOF without preceding newline in C

前端 未结 2 514
盖世英雄少女心
盖世英雄少女心 2021-01-16 13:02

Lets say I have the below C code:

int getLine (char line[])
{
    int c, i=0;
    while( (c=getchar()) != EOF )
           line[i++]=c;
    line[i++] = c;
           


        
相关标签:
2条回答
  • 2021-01-16 13:08

    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.

    0 讨论(0)
  • 2021-01-16 13:19

    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.

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