Почему мой getline () не читает первую строку моего стандартного ввода в C? - PullRequest
0 голосов
/ 19 апреля 2020

Я относительно новичок в C и использую функцию getline() для чтения содержимого файла, поставляемого в качестве стандартного ввода.

Однако while l oop не читает первую строку файла, и я не уверен, почему!

Для контекста: файл читает-

a b c
-d e 
f

И вывод читает и разделяет -d, e & f правильно, но печатает только a b c вне while l oop.

int main (){

//utilising data provided at http://www.linux.die.net/man/3/getline
//char*linePointer is initialized to NULL, for getline() to allocate a buffer that stores the line
//buffer gets resized dynamically 

char *linePointer = NULL; 
size_t len = 0;

//checks if the file is empty and prints -, if it is
if ((getline(&linePointer, &len, stdin) == -1)){
    printf("-\n");
}

//as long as the stream is valid, and the file can be read 
//if either of the conditions are not satisfied then while loop condition is not satisfied 
//prints the contents of the line 

Clauses cs = createNewArrayList();
printf("%s\n", linePointer);
while ((getline(&linePointer, &len, stdin) != -1)){
        printf("%s\n", linePointer);

    Clause c = createNewArrayList();
    char *token; 
    char *delim = " ";
    token = strtok(linePointer, delim);
    while (token != NULL){      
        char *duplicate = strdup(token);     
        add(c, duplicate);
        printf("%s\n",duplicate);
        token = strtok(NULL, delim);
    }
    add(cs, c);
}

free(linePointer);
exit(EXIT_SUCCESS);    

Ответы [ 2 ]

1 голос
/ 19 апреля 2020

Поскольку ваш первый getline использует первую строку:

//checks if the file is empty and prints -, if it is
if ((getline(&linePointer, &len, stdin) == -1)){
    printf("-\n");
}

while l oop снова запускает getline и игнорирует результат этого первого запуска.

0 голосов
/ 19 апреля 2020

Вы читаете и отбрасываете 1-ю строку перед вводом while l oop, поэтому l oop не видит эту строку.

Попробуйте вместо этого:

int main (){

    //utilising data provided at http://www.linux.die.net/man/3/getline
    //char*linePointer is initialized to NULL, for getline() to allocate a buffer that stores the line
    //buffer gets resized dynamically 

    char *linePointer = NULL; 
    size_t len = 0;

    //checks if the file is empty and prints -, if it is
    if ((getline(&linePointer, &len, stdin) == -1)){
        printf("-\n");
    }
    else{
        //as long as the stream is valid, and the file can be read 
        //if either of the conditions are not satisfied then while loop condition is not satisfied 
        //prints the contents of the line 

        Clauses cs = createNewArrayList();
        do{
            printf("%s\n", linePointer);

            Clause c = createNewArrayList();
            char *delim = " ";
            char *token = strtok(linePointer, delim);
            while (token != NULL){      
                char *duplicate = strdup(token);     
                add(c, duplicate);
                printf("%s\n",duplicate);
                //if add() makes its own copy, then uncomment this,
                //or simply don't use strdup() above to begin with:
                //free(duplicate);
                token = strtok(NULL, delim);
            }
            add(cs, c);

            free(linePointer);
            linePointer = NULL; 
            len = 0;
        }
        while (getline(&linePointer, &len, stdin) != -1);
    }

    free(linePointer);
    exit(EXIT_SUCCESS);
}
...