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

问题描述

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

What is the simplest way to read a full line in a C console programThe 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中的控制台读取一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:30