如何从 C 中的控制台读取一行? [英] How to read a line from the console in C?

查看:68
本文介绍了如何从 C 中的控制台读取一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 控制台程序中读取整行的最简单方法是什么输入的文本可能具有可变长度,我们无法对其内容做出任何假设.

What is the simplest way to read a full line in a C console program The text entered might have a variable length and we can't make any assumption about its content.

推荐答案

您需要动态内存管理,并使用 fgets 函数来读取您的行.但是,似乎无法查看它读取了多少个字符.所以你使用 fgetc:

You need dynamic memory management, and use the fgets function to read your line. However, there seems to be no way to see how many characters it read. So you use fgetc:

char * getline(void) {
    char * line = malloc(100), * linep = line;
    size_t lenmax = 100, len = lenmax;
    int c;

    if(line == NULL)
        return NULL;

    for(;;) {
        c = fgetc(stdin);
        if(c == EOF)
            break;

        if(--len == 0) {
            len = lenmax;
            char * linen = realloc(linep, lenmax *= 2);

            if(linen == NULL) {
                free(linep);
                return NULL;
            }
            line = linen + (line - linep);
            linep = linen;
        }

        if((*line++ = c) == '
')
            break;
    }
    *line = '';
    return linep;
}

注意:千万不要使用gets!它不做边界检查,并且会溢出你的缓冲区

Note: Never use gets ! It does not do bounds checking and can overflow your buffer

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

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