如何阅读在C中的控制台线? [英] How to read a line from the console in C?

查看:110
本文介绍了如何阅读在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 函数读取您的线路。然而,似乎没有办法,看看有多少个字符读取。所以,你使用龟etc:

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) == '\n')
            break;
    }
    *line = '\0';
    return linep;
}

注意:切勿使用得到!它不会做边界检查,可以溢出您的缓冲区

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

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

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