如何从stdin中读取一行,阻塞直到找到换行符? [英] How to read a line from stdin, blocking until the newline is found?

查看:51
本文介绍了如何从stdin中读取一行,阻塞直到找到换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一次从命令行的stdin读取任意长度的一行.我不确定我是否能够包含GNU readline并希望使用库函数.

I'm trying to read one line at a time, of arbitrary length, from stdin at the command line. I'm not sure if I'll be able to include GNU readline and would prefer to use a library function.

我阅读的文档表明 getline 应该可以工作,但是在我的实验中却没有阻止.我的示例程序:

The documentation I've read suggests that getline ought to work, but in my experiments it doesn't block. My sample program:

#include <stdio.h>
int main()
{
    char *line = NULL;
    if (getline(&line, NULL, stdin) == -1) {
        printf("No line\n");
    } else {
        printf("%s\n", line);
    }
    return 0;
}

产生无行,这使其不适合接受用户输入.

produces No line, which makes it unsuitable for accepting user input.

我该怎么做?我知道这应该是微不足道的,但我一直无法弄清楚.

How do I do this? I know it should be trivial, but I haven't been able to figure it out.

推荐答案

尝试此补丁

char *line = NULL;
+size_t size;
+if (getline(&line, &size, stdin) == -1) {
-if (getline(&line, 0, stdin) == -1) {
    printf("No line\n");
} else {

这篇关于如何从stdin中读取一行,阻塞直到找到换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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