Try to search your question here, if you can't find : Ask Any Question Now ?

Function iterates the same input recieved from text file

HomeCategory: stackoverflowFunction iterates the same input recieved from text file
Avatarpushpa asked 2 weeks ago

This function should read a single line input from a file called "newtext.txt" (defined by path in my code), extract the first word in said line and use it as the name field for each element of a linked list (which is then printed).

This is code I wrote:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct user {

    char name[50];
    struct user* next;
};

int main() {

    unsigned i = 0;
    struct user *temp = NULL
    struct user *aux = NULL;


    FILE* file_pointer = fopen("/home/marco/Desktop/suite1/newtext.txt", "r");

    if(file_pointer == NULL) {

        printf("nWarning! File not opened properly!n");

        return -1;
    }

    char vector[100];
    char sub_v[50];

    while(fgets(vector, sizeof(vector), file_pointer) != NULL) {

        while(vector[i] != ' ' && i < (sizeof(sub_v) - 1)) {

            sub_v[i] = vector[i];
            i++;
        }

        sub_v[i] = '';
        i++;

        if(temp == NULL) {      //first element in the list;

            temp = malloc(sizeof(struct user));
            aux = temp;
            strcpy(temp -> name, sub_v);
            temp -> next = NULL;

        } else {

            temp -> next = malloc(sizeof(struct user));
            temp = temp -> next;
            temp -> next = NULL;
            strcpy(temp -> name, sub_v);
        }
    }

    while(aux != NULL) {

        puts(aux -> name);
        aux = aux -> next;
    }

    fclose(file_pointer);

    return 0;
}

the file included is:

andrew michael jonathan
frank
marcus raquis
freddie

And the expected output should be:

andrew
frank
marcus
freddie

but it is:

andrew
andrew
andrew
andrew

It appears the while cycle is repeated with the same imput line, but I don’t know how to fix this issue.

1 Answers
Best Answer
AvatarMikhail answered 2 weeks ago
Your Answer

16 + 2 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com