使用fgets()和stdin作为输入:^ D未能发出EOF信号 [英] using fgets() with stdin as input: ^D fails to signal EOF

查看:150
本文介绍了使用fgets()和stdin作为输入:^ D未能发出EOF信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在MacBook上使用Mojave在C语言中编写一个程序,我试图使用fgets()从stdin中获取字符串。

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.

我的代码编译-唯一的问题是,当我在终端中运行程序时,在调用fgets()并键入所需的输入后,我不知道如何用信号通知输入结束,以便程序可以继续运行。

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.

我已经检查了fgets()的文档,其中说:

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


fgets()读入的内容最多小于调整流中的字符大小并将其存储到s所指向的缓冲区中。在* EOF *或换行符之后读取停止。如果读取了换行符,则将其存储到缓冲区中。将存储一个终止的空字节(\0)在缓冲区中的最后一个字符之后。 -来自此页面

在终端中输入'stty all'表明EOF确实对应于^ D。我试过两次输入^ D,三次,按Enter再按^ D,^ D再按Enter,依此类推。等等。似乎什么都不起作用。

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;
}


推荐答案

您不测试返回值 fgets()的值:如果确实从终端发出信号文件结束,则随后对 fgets()将返回 NULL 并且目标数组将保持未初始化状态。

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.

您的代码中没有任何东西可以阻止程序文件末尾的操作。只需在每个输入项后按Enter键。为什么您认为需要文件结尾信号

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?

这篇关于使用fgets()和stdin作为输入:^ D未能发出EOF信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆