Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use scanf to read lines or break on special character

Tags:

c

scanf

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

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?

like image 721
Iluvatar Avatar asked Dec 24 '16 17:12

Iluvatar


1 Answers

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.

like image 103
user2736738 Avatar answered Oct 29 '22 21:10

user2736738