使用 scanf 读取行或中断特殊字符 [英] Use scanf to read lines or break on special character

查看:69
本文介绍了使用 scanf 读取行或中断特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 scanf() 读取文本行 - 不包括 \n 并在特殊(选择的)字符上中断,但包括该字符

Is it possible to read lines of text with scanf() - excluding \n and break on special(chosen) character, but include that character

这是我当前的表达式:while(scanf("%49[^:\n]%*c", x)==1)但是这个不包括 :.是否可以在 : 上中断读取但也读取该字符?

This is my current expression: while(scanf("%49[^:\n]%*c", x)==1) but this one excludes :. Is it possible to break reading on : but read that character too?

推荐答案

好的,我正在使用 Johannes-Schaub-litb 的 代码.

Ok I am using Johannes-Schaub-litb's code.

char * getline(char cp) {
    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;
            intptr_t diff = line - linep;
            char * linen = realloc(linep, lenmax *= 2);

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

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

我仍然使用这个代码......它工作正常.代码稍后会稍微修改一下.

Still I use this code ...and it works fine. The code will be modified a bit more later.

这篇关于使用 scanf 读取行或中断特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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