using fgets() with stdin as input: ^D fails to sig

2019-07-29 16:18发布

问题:

I'm writing a program in C on my MacBook which uses Mojave and I'm trying to use fgets() to get a string from stdin.

My code compiles - the only issue is that when I run the program in the terminal, after fgets() is called and I type in the desired input, I can't figure out how to signal the end of the input so that the program can continue running.

I recognise many people have had this issue and that there are many pages on this site addressing it. But none of the solutions (that I have understood) have worked for me. I've read this and this but these aren't helping.

I've checked out the documentation for fgets() which says:

"fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an *EOF* or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (\0) is stored after the last character in the buffer." - from this page.

Entering 'stty all' in the terminal shows that EOF indeed corresponds to ^D. I've tried entering ^D twice, three times, pressing Enter then ^D, ^D then Enter, etc. etc. Nothing seems to work.

What am I doing wrong? Here's the relevant bit of the code (originally from here, under the 'Pointers to Structures Containing Pointers' section):

#include <stdio.h>

typedef struct
{
    char name[21];
    char city[21];
    char phone[21];
    char *comment;
} Address;


int main(void)
{
    Address s;
    char comm[100];

    fgets(s.name, 20, stdin);
    fgets(s.city, 20, stdin);
    fgets(s.phone, 20, stdin);
    fgets(comm, 100, stdin);

    return 0;
}

回答1:

You do not test the return value of fgets(): if you indeed signal an end of file from the terminal, the subsequent calls to fgets() will return NULL and the destination arrays will be left uninitialized.

There is nothing in your code that prevents program operation at end of file. Just hit enter after each piece of input. Why do you think you need to signal end of file?



标签: c fgets eof