Not reading number properly?












0















I'm trying to read from file line by line. It takes the first number of the line and the rest it connects it using a char of linked list. But when I run it, i get the connection as -38 (which is wrong) and it only prints it once and does not go through the rest of the line. but it reads first element perfectly.



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

struct node{
int data;
struct node* next;
};


int main(void)
{
FILE * fp;
char * line = NULL;
char * storage;
size_t len = 0;
ssize_t read;
struct node *G[1000];
for (int i = 1; i < 1000; i++)
{
G[i]= malloc(sizeof(struct node));
G[i]->data = i;
G[i]->next = NULL;
}

fp = fopen("idk2.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);

while ((read = getline(&line, &len, fp)) != -1) {
int vertexGettingConntected = line[0];
struct node* newItem;
printf("Retrieved line of length %zu :", read);
int i = 0;
while(line[i] != ''){
if ( line[i] == ' '){
i++;
}
else if (i == 0){
newItem = malloc(sizeof(struct node));
int itemStorage = line[0] - '0';
newItem->next = NULL;
newItem->data = itemStorage;
G[itemStorage] = newItem;
printf("This is first Number:%dn", itemStorage);
}
else if (line[i] != ' '){
struct node* addingItem = newItem;
while(addingItem->next != NULL){
addingItem = addingItem->next;
}
int itemStorage = line[i] - '0';
struct node* newConnection = malloc(sizeof(struct node));
addingItem->next = newConnection;
newConnection->data = itemStorage;
newConnection->next = NULL;
printf("This is character:%cn", line[i]);
printf("This is connection:%in", itemStorage);
}
i++;
}
}

fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
for(int printer = 1; printer<20; printer++){
printf("%dn",G[printer]->data);
}
}


EDIT:
Just wanted to include file im reading from:



1 3 4
2 4
3 1 4
4 2 1 3









share|improve this question

























  • First of all, line is never allocated any space that I can see, so you have undefined behavior. Literally anything can happen. Where is getline() defined?

    – torstenvl
    Nov 14 '18 at 2:23








  • 2





    @torstenvl getline() allocates mem.

    – Swordfish
    Nov 14 '18 at 2:24






  • 1





    @NeverSleepAlwaysCode Why is your code one sole spaghetti in main? Don't you know how to write functions yet?

    – Swordfish
    Nov 14 '18 at 2:25











  • @Swordfish I am required by my professor to write the read in file in the main. I had divided my code before into functions and lost 20 points for not following guidelines which makes it confusing for me.

    – NeverSleepAlwaysCode
    Nov 14 '18 at 2:27











  • Ideally, i would prefer to have a separate function to read file and another to allocate into array.

    – NeverSleepAlwaysCode
    Nov 14 '18 at 2:28
















0















I'm trying to read from file line by line. It takes the first number of the line and the rest it connects it using a char of linked list. But when I run it, i get the connection as -38 (which is wrong) and it only prints it once and does not go through the rest of the line. but it reads first element perfectly.



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

struct node{
int data;
struct node* next;
};


int main(void)
{
FILE * fp;
char * line = NULL;
char * storage;
size_t len = 0;
ssize_t read;
struct node *G[1000];
for (int i = 1; i < 1000; i++)
{
G[i]= malloc(sizeof(struct node));
G[i]->data = i;
G[i]->next = NULL;
}

fp = fopen("idk2.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);

while ((read = getline(&line, &len, fp)) != -1) {
int vertexGettingConntected = line[0];
struct node* newItem;
printf("Retrieved line of length %zu :", read);
int i = 0;
while(line[i] != ''){
if ( line[i] == ' '){
i++;
}
else if (i == 0){
newItem = malloc(sizeof(struct node));
int itemStorage = line[0] - '0';
newItem->next = NULL;
newItem->data = itemStorage;
G[itemStorage] = newItem;
printf("This is first Number:%dn", itemStorage);
}
else if (line[i] != ' '){
struct node* addingItem = newItem;
while(addingItem->next != NULL){
addingItem = addingItem->next;
}
int itemStorage = line[i] - '0';
struct node* newConnection = malloc(sizeof(struct node));
addingItem->next = newConnection;
newConnection->data = itemStorage;
newConnection->next = NULL;
printf("This is character:%cn", line[i]);
printf("This is connection:%in", itemStorage);
}
i++;
}
}

fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
for(int printer = 1; printer<20; printer++){
printf("%dn",G[printer]->data);
}
}


EDIT:
Just wanted to include file im reading from:



1 3 4
2 4
3 1 4
4 2 1 3









share|improve this question

























  • First of all, line is never allocated any space that I can see, so you have undefined behavior. Literally anything can happen. Where is getline() defined?

    – torstenvl
    Nov 14 '18 at 2:23








  • 2





    @torstenvl getline() allocates mem.

    – Swordfish
    Nov 14 '18 at 2:24






  • 1





    @NeverSleepAlwaysCode Why is your code one sole spaghetti in main? Don't you know how to write functions yet?

    – Swordfish
    Nov 14 '18 at 2:25











  • @Swordfish I am required by my professor to write the read in file in the main. I had divided my code before into functions and lost 20 points for not following guidelines which makes it confusing for me.

    – NeverSleepAlwaysCode
    Nov 14 '18 at 2:27











  • Ideally, i would prefer to have a separate function to read file and another to allocate into array.

    – NeverSleepAlwaysCode
    Nov 14 '18 at 2:28














0












0








0








I'm trying to read from file line by line. It takes the first number of the line and the rest it connects it using a char of linked list. But when I run it, i get the connection as -38 (which is wrong) and it only prints it once and does not go through the rest of the line. but it reads first element perfectly.



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

struct node{
int data;
struct node* next;
};


int main(void)
{
FILE * fp;
char * line = NULL;
char * storage;
size_t len = 0;
ssize_t read;
struct node *G[1000];
for (int i = 1; i < 1000; i++)
{
G[i]= malloc(sizeof(struct node));
G[i]->data = i;
G[i]->next = NULL;
}

fp = fopen("idk2.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);

while ((read = getline(&line, &len, fp)) != -1) {
int vertexGettingConntected = line[0];
struct node* newItem;
printf("Retrieved line of length %zu :", read);
int i = 0;
while(line[i] != ''){
if ( line[i] == ' '){
i++;
}
else if (i == 0){
newItem = malloc(sizeof(struct node));
int itemStorage = line[0] - '0';
newItem->next = NULL;
newItem->data = itemStorage;
G[itemStorage] = newItem;
printf("This is first Number:%dn", itemStorage);
}
else if (line[i] != ' '){
struct node* addingItem = newItem;
while(addingItem->next != NULL){
addingItem = addingItem->next;
}
int itemStorage = line[i] - '0';
struct node* newConnection = malloc(sizeof(struct node));
addingItem->next = newConnection;
newConnection->data = itemStorage;
newConnection->next = NULL;
printf("This is character:%cn", line[i]);
printf("This is connection:%in", itemStorage);
}
i++;
}
}

fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
for(int printer = 1; printer<20; printer++){
printf("%dn",G[printer]->data);
}
}


EDIT:
Just wanted to include file im reading from:



1 3 4
2 4
3 1 4
4 2 1 3









share|improve this question
















I'm trying to read from file line by line. It takes the first number of the line and the rest it connects it using a char of linked list. But when I run it, i get the connection as -38 (which is wrong) and it only prints it once and does not go through the rest of the line. but it reads first element perfectly.



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

struct node{
int data;
struct node* next;
};


int main(void)
{
FILE * fp;
char * line = NULL;
char * storage;
size_t len = 0;
ssize_t read;
struct node *G[1000];
for (int i = 1; i < 1000; i++)
{
G[i]= malloc(sizeof(struct node));
G[i]->data = i;
G[i]->next = NULL;
}

fp = fopen("idk2.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);

while ((read = getline(&line, &len, fp)) != -1) {
int vertexGettingConntected = line[0];
struct node* newItem;
printf("Retrieved line of length %zu :", read);
int i = 0;
while(line[i] != ''){
if ( line[i] == ' '){
i++;
}
else if (i == 0){
newItem = malloc(sizeof(struct node));
int itemStorage = line[0] - '0';
newItem->next = NULL;
newItem->data = itemStorage;
G[itemStorage] = newItem;
printf("This is first Number:%dn", itemStorage);
}
else if (line[i] != ' '){
struct node* addingItem = newItem;
while(addingItem->next != NULL){
addingItem = addingItem->next;
}
int itemStorage = line[i] - '0';
struct node* newConnection = malloc(sizeof(struct node));
addingItem->next = newConnection;
newConnection->data = itemStorage;
newConnection->next = NULL;
printf("This is character:%cn", line[i]);
printf("This is connection:%in", itemStorage);
}
i++;
}
}

fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
for(int printer = 1; printer<20; printer++){
printf("%dn",G[printer]->data);
}
}


EDIT:
Just wanted to include file im reading from:



1 3 4
2 4
3 1 4
4 2 1 3






c file






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 3:06







NeverSleepAlwaysCode

















asked Nov 14 '18 at 2:04









NeverSleepAlwaysCodeNeverSleepAlwaysCode

216




216













  • First of all, line is never allocated any space that I can see, so you have undefined behavior. Literally anything can happen. Where is getline() defined?

    – torstenvl
    Nov 14 '18 at 2:23








  • 2





    @torstenvl getline() allocates mem.

    – Swordfish
    Nov 14 '18 at 2:24






  • 1





    @NeverSleepAlwaysCode Why is your code one sole spaghetti in main? Don't you know how to write functions yet?

    – Swordfish
    Nov 14 '18 at 2:25











  • @Swordfish I am required by my professor to write the read in file in the main. I had divided my code before into functions and lost 20 points for not following guidelines which makes it confusing for me.

    – NeverSleepAlwaysCode
    Nov 14 '18 at 2:27











  • Ideally, i would prefer to have a separate function to read file and another to allocate into array.

    – NeverSleepAlwaysCode
    Nov 14 '18 at 2:28



















  • First of all, line is never allocated any space that I can see, so you have undefined behavior. Literally anything can happen. Where is getline() defined?

    – torstenvl
    Nov 14 '18 at 2:23








  • 2





    @torstenvl getline() allocates mem.

    – Swordfish
    Nov 14 '18 at 2:24






  • 1





    @NeverSleepAlwaysCode Why is your code one sole spaghetti in main? Don't you know how to write functions yet?

    – Swordfish
    Nov 14 '18 at 2:25











  • @Swordfish I am required by my professor to write the read in file in the main. I had divided my code before into functions and lost 20 points for not following guidelines which makes it confusing for me.

    – NeverSleepAlwaysCode
    Nov 14 '18 at 2:27











  • Ideally, i would prefer to have a separate function to read file and another to allocate into array.

    – NeverSleepAlwaysCode
    Nov 14 '18 at 2:28

















First of all, line is never allocated any space that I can see, so you have undefined behavior. Literally anything can happen. Where is getline() defined?

– torstenvl
Nov 14 '18 at 2:23







First of all, line is never allocated any space that I can see, so you have undefined behavior. Literally anything can happen. Where is getline() defined?

– torstenvl
Nov 14 '18 at 2:23






2




2





@torstenvl getline() allocates mem.

– Swordfish
Nov 14 '18 at 2:24





@torstenvl getline() allocates mem.

– Swordfish
Nov 14 '18 at 2:24




1




1





@NeverSleepAlwaysCode Why is your code one sole spaghetti in main? Don't you know how to write functions yet?

– Swordfish
Nov 14 '18 at 2:25





@NeverSleepAlwaysCode Why is your code one sole spaghetti in main? Don't you know how to write functions yet?

– Swordfish
Nov 14 '18 at 2:25













@Swordfish I am required by my professor to write the read in file in the main. I had divided my code before into functions and lost 20 points for not following guidelines which makes it confusing for me.

– NeverSleepAlwaysCode
Nov 14 '18 at 2:27





@Swordfish I am required by my professor to write the read in file in the main. I had divided my code before into functions and lost 20 points for not following guidelines which makes it confusing for me.

– NeverSleepAlwaysCode
Nov 14 '18 at 2:27













Ideally, i would prefer to have a separate function to read file and another to allocate into array.

– NeverSleepAlwaysCode
Nov 14 '18 at 2:28





Ideally, i would prefer to have a separate function to read file and another to allocate into array.

– NeverSleepAlwaysCode
Nov 14 '18 at 2:28












2 Answers
2






active

oldest

votes


















0














I am not sure why you want to have an array of pointers to node which you all allocate memory for at the beginning of your program without knowing how many nodes will be needed. Then you allocate memory again while reading from the file.



Given the constraints of not being allowed to use functions, thats how i'd read the file and build a list:



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

typedef struct node_tag {
int value;
struct node_tag *next;
} node_t;

int main(void)
{
char const *filename = "test.txt";
FILE *input_file = fopen(filename, "r");
if (!input_file) {
fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
return EXIT_FAILURE;
}

// read from file and build a list:
node_t *head = NULL;
node_t *tail = NULL;
int value;
int result = EXIT_SUCCESS;

while (fscanf(input_file, "%d", &value) == 1) {
node_t *new_node = calloc(1, sizeof *new_node);
if (!new_node) {
fputs("Not enough memory :(nn", stderr);
result = EXIT_FAILURE;
goto glean_up;
}

new_node->value = value;

if (!head) { // there is no head yet so new_node becomes the head
head = tail = new_node; // which is also the lists tail
continue;
}

tail->next = new_node;
tail = new_node;
}

// print the list:
for (node_t *current_node = head; current_node; current_node = current_node->next)
printf("%d ", current_node->value);
putchar('n');


clean_up:
fclose(input_file);

for (node_t *current_node = head, *temp; current_node; current_node = temp) {
temp = current_node->next;
free(current_node);
}

return result;
}


Ideally you'd write functions to manage the list:



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

typedef struct node_tag {
int value;
struct node_tag *next;
} node_t;

typedef struct list_tag {
node_t *head;
node_t *tail;
} list_t;

void list_create(list_t *list)
{
list->head = list->tail = NULL;
}

bool list_push_back(list_t *list, int value)
{
node_t *new_node = calloc(1, sizeof *new_node);
if (!new_node)
return false;

new_node->value = value;

if (!list->head) {
list->head = list->tail = new_node;
return true;
}

list->tail->next = new_node;
list->tail = new_node;
return true;
}

void list_print(list_t *list)
{
for (node_t *current_node = list->head; current_node; current_node = current_node->next)
printf("%d ", current_node->value);
}

void list_free(list_t *list)
{
for (node_t *current_node = list->head, *temp; current_node; current_node = temp) {
temp = current_node->next;
free(current_node);
}
}

bool read_int(FILE *input_file, int *value)
{
return fscanf(input_file, "%d", value) == 1;
}

int main(void)
{
char const *filename = "test.txt";
FILE *input_file = fopen(filename, "r");
if (!input_file) {
fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
return EXIT_FAILURE;
}

// read from file and build a list:
list_t list;
list_create(&list);
int value;

while (read_int(input_file, &value)) {
if (!list_push_back(&list, value)) {
fputs("Not enough memory :(nn", stderr);
// clean up:
fclose(input_file);
list_free(&list);
return EXIT_FAILURE;
}
}

// print the list:
list_print(&list);
putchar('n');

// clean up:
fclose(input_file);
list_free(&list);
}


Output:



1 3 4 2 4 3 1 4 4 2 1 3





share|improve this answer

































    0














    When you hit a space character you iterate i. At the end of your loop you iterate i.



    So when you hit a space character you iterate i twice, skipping the number and landing on the next space character.



    Which is why you get the first number but miss the rest.



    edit: removed getline() comments due to feedback from @swordfish. Current implementation is not problematic.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292164%2fnot-reading-number-properly%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      I am not sure why you want to have an array of pointers to node which you all allocate memory for at the beginning of your program without knowing how many nodes will be needed. Then you allocate memory again while reading from the file.



      Given the constraints of not being allowed to use functions, thats how i'd read the file and build a list:



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

      typedef struct node_tag {
      int value;
      struct node_tag *next;
      } node_t;

      int main(void)
      {
      char const *filename = "test.txt";
      FILE *input_file = fopen(filename, "r");
      if (!input_file) {
      fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
      return EXIT_FAILURE;
      }

      // read from file and build a list:
      node_t *head = NULL;
      node_t *tail = NULL;
      int value;
      int result = EXIT_SUCCESS;

      while (fscanf(input_file, "%d", &value) == 1) {
      node_t *new_node = calloc(1, sizeof *new_node);
      if (!new_node) {
      fputs("Not enough memory :(nn", stderr);
      result = EXIT_FAILURE;
      goto glean_up;
      }

      new_node->value = value;

      if (!head) { // there is no head yet so new_node becomes the head
      head = tail = new_node; // which is also the lists tail
      continue;
      }

      tail->next = new_node;
      tail = new_node;
      }

      // print the list:
      for (node_t *current_node = head; current_node; current_node = current_node->next)
      printf("%d ", current_node->value);
      putchar('n');


      clean_up:
      fclose(input_file);

      for (node_t *current_node = head, *temp; current_node; current_node = temp) {
      temp = current_node->next;
      free(current_node);
      }

      return result;
      }


      Ideally you'd write functions to manage the list:



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

      typedef struct node_tag {
      int value;
      struct node_tag *next;
      } node_t;

      typedef struct list_tag {
      node_t *head;
      node_t *tail;
      } list_t;

      void list_create(list_t *list)
      {
      list->head = list->tail = NULL;
      }

      bool list_push_back(list_t *list, int value)
      {
      node_t *new_node = calloc(1, sizeof *new_node);
      if (!new_node)
      return false;

      new_node->value = value;

      if (!list->head) {
      list->head = list->tail = new_node;
      return true;
      }

      list->tail->next = new_node;
      list->tail = new_node;
      return true;
      }

      void list_print(list_t *list)
      {
      for (node_t *current_node = list->head; current_node; current_node = current_node->next)
      printf("%d ", current_node->value);
      }

      void list_free(list_t *list)
      {
      for (node_t *current_node = list->head, *temp; current_node; current_node = temp) {
      temp = current_node->next;
      free(current_node);
      }
      }

      bool read_int(FILE *input_file, int *value)
      {
      return fscanf(input_file, "%d", value) == 1;
      }

      int main(void)
      {
      char const *filename = "test.txt";
      FILE *input_file = fopen(filename, "r");
      if (!input_file) {
      fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
      return EXIT_FAILURE;
      }

      // read from file and build a list:
      list_t list;
      list_create(&list);
      int value;

      while (read_int(input_file, &value)) {
      if (!list_push_back(&list, value)) {
      fputs("Not enough memory :(nn", stderr);
      // clean up:
      fclose(input_file);
      list_free(&list);
      return EXIT_FAILURE;
      }
      }

      // print the list:
      list_print(&list);
      putchar('n');

      // clean up:
      fclose(input_file);
      list_free(&list);
      }


      Output:



      1 3 4 2 4 3 1 4 4 2 1 3





      share|improve this answer






























        0














        I am not sure why you want to have an array of pointers to node which you all allocate memory for at the beginning of your program without knowing how many nodes will be needed. Then you allocate memory again while reading from the file.



        Given the constraints of not being allowed to use functions, thats how i'd read the file and build a list:



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

        typedef struct node_tag {
        int value;
        struct node_tag *next;
        } node_t;

        int main(void)
        {
        char const *filename = "test.txt";
        FILE *input_file = fopen(filename, "r");
        if (!input_file) {
        fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
        return EXIT_FAILURE;
        }

        // read from file and build a list:
        node_t *head = NULL;
        node_t *tail = NULL;
        int value;
        int result = EXIT_SUCCESS;

        while (fscanf(input_file, "%d", &value) == 1) {
        node_t *new_node = calloc(1, sizeof *new_node);
        if (!new_node) {
        fputs("Not enough memory :(nn", stderr);
        result = EXIT_FAILURE;
        goto glean_up;
        }

        new_node->value = value;

        if (!head) { // there is no head yet so new_node becomes the head
        head = tail = new_node; // which is also the lists tail
        continue;
        }

        tail->next = new_node;
        tail = new_node;
        }

        // print the list:
        for (node_t *current_node = head; current_node; current_node = current_node->next)
        printf("%d ", current_node->value);
        putchar('n');


        clean_up:
        fclose(input_file);

        for (node_t *current_node = head, *temp; current_node; current_node = temp) {
        temp = current_node->next;
        free(current_node);
        }

        return result;
        }


        Ideally you'd write functions to manage the list:



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

        typedef struct node_tag {
        int value;
        struct node_tag *next;
        } node_t;

        typedef struct list_tag {
        node_t *head;
        node_t *tail;
        } list_t;

        void list_create(list_t *list)
        {
        list->head = list->tail = NULL;
        }

        bool list_push_back(list_t *list, int value)
        {
        node_t *new_node = calloc(1, sizeof *new_node);
        if (!new_node)
        return false;

        new_node->value = value;

        if (!list->head) {
        list->head = list->tail = new_node;
        return true;
        }

        list->tail->next = new_node;
        list->tail = new_node;
        return true;
        }

        void list_print(list_t *list)
        {
        for (node_t *current_node = list->head; current_node; current_node = current_node->next)
        printf("%d ", current_node->value);
        }

        void list_free(list_t *list)
        {
        for (node_t *current_node = list->head, *temp; current_node; current_node = temp) {
        temp = current_node->next;
        free(current_node);
        }
        }

        bool read_int(FILE *input_file, int *value)
        {
        return fscanf(input_file, "%d", value) == 1;
        }

        int main(void)
        {
        char const *filename = "test.txt";
        FILE *input_file = fopen(filename, "r");
        if (!input_file) {
        fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
        return EXIT_FAILURE;
        }

        // read from file and build a list:
        list_t list;
        list_create(&list);
        int value;

        while (read_int(input_file, &value)) {
        if (!list_push_back(&list, value)) {
        fputs("Not enough memory :(nn", stderr);
        // clean up:
        fclose(input_file);
        list_free(&list);
        return EXIT_FAILURE;
        }
        }

        // print the list:
        list_print(&list);
        putchar('n');

        // clean up:
        fclose(input_file);
        list_free(&list);
        }


        Output:



        1 3 4 2 4 3 1 4 4 2 1 3





        share|improve this answer




























          0












          0








          0







          I am not sure why you want to have an array of pointers to node which you all allocate memory for at the beginning of your program without knowing how many nodes will be needed. Then you allocate memory again while reading from the file.



          Given the constraints of not being allowed to use functions, thats how i'd read the file and build a list:



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

          typedef struct node_tag {
          int value;
          struct node_tag *next;
          } node_t;

          int main(void)
          {
          char const *filename = "test.txt";
          FILE *input_file = fopen(filename, "r");
          if (!input_file) {
          fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
          return EXIT_FAILURE;
          }

          // read from file and build a list:
          node_t *head = NULL;
          node_t *tail = NULL;
          int value;
          int result = EXIT_SUCCESS;

          while (fscanf(input_file, "%d", &value) == 1) {
          node_t *new_node = calloc(1, sizeof *new_node);
          if (!new_node) {
          fputs("Not enough memory :(nn", stderr);
          result = EXIT_FAILURE;
          goto glean_up;
          }

          new_node->value = value;

          if (!head) { // there is no head yet so new_node becomes the head
          head = tail = new_node; // which is also the lists tail
          continue;
          }

          tail->next = new_node;
          tail = new_node;
          }

          // print the list:
          for (node_t *current_node = head; current_node; current_node = current_node->next)
          printf("%d ", current_node->value);
          putchar('n');


          clean_up:
          fclose(input_file);

          for (node_t *current_node = head, *temp; current_node; current_node = temp) {
          temp = current_node->next;
          free(current_node);
          }

          return result;
          }


          Ideally you'd write functions to manage the list:



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

          typedef struct node_tag {
          int value;
          struct node_tag *next;
          } node_t;

          typedef struct list_tag {
          node_t *head;
          node_t *tail;
          } list_t;

          void list_create(list_t *list)
          {
          list->head = list->tail = NULL;
          }

          bool list_push_back(list_t *list, int value)
          {
          node_t *new_node = calloc(1, sizeof *new_node);
          if (!new_node)
          return false;

          new_node->value = value;

          if (!list->head) {
          list->head = list->tail = new_node;
          return true;
          }

          list->tail->next = new_node;
          list->tail = new_node;
          return true;
          }

          void list_print(list_t *list)
          {
          for (node_t *current_node = list->head; current_node; current_node = current_node->next)
          printf("%d ", current_node->value);
          }

          void list_free(list_t *list)
          {
          for (node_t *current_node = list->head, *temp; current_node; current_node = temp) {
          temp = current_node->next;
          free(current_node);
          }
          }

          bool read_int(FILE *input_file, int *value)
          {
          return fscanf(input_file, "%d", value) == 1;
          }

          int main(void)
          {
          char const *filename = "test.txt";
          FILE *input_file = fopen(filename, "r");
          if (!input_file) {
          fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
          return EXIT_FAILURE;
          }

          // read from file and build a list:
          list_t list;
          list_create(&list);
          int value;

          while (read_int(input_file, &value)) {
          if (!list_push_back(&list, value)) {
          fputs("Not enough memory :(nn", stderr);
          // clean up:
          fclose(input_file);
          list_free(&list);
          return EXIT_FAILURE;
          }
          }

          // print the list:
          list_print(&list);
          putchar('n');

          // clean up:
          fclose(input_file);
          list_free(&list);
          }


          Output:



          1 3 4 2 4 3 1 4 4 2 1 3





          share|improve this answer















          I am not sure why you want to have an array of pointers to node which you all allocate memory for at the beginning of your program without knowing how many nodes will be needed. Then you allocate memory again while reading from the file.



          Given the constraints of not being allowed to use functions, thats how i'd read the file and build a list:



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

          typedef struct node_tag {
          int value;
          struct node_tag *next;
          } node_t;

          int main(void)
          {
          char const *filename = "test.txt";
          FILE *input_file = fopen(filename, "r");
          if (!input_file) {
          fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
          return EXIT_FAILURE;
          }

          // read from file and build a list:
          node_t *head = NULL;
          node_t *tail = NULL;
          int value;
          int result = EXIT_SUCCESS;

          while (fscanf(input_file, "%d", &value) == 1) {
          node_t *new_node = calloc(1, sizeof *new_node);
          if (!new_node) {
          fputs("Not enough memory :(nn", stderr);
          result = EXIT_FAILURE;
          goto glean_up;
          }

          new_node->value = value;

          if (!head) { // there is no head yet so new_node becomes the head
          head = tail = new_node; // which is also the lists tail
          continue;
          }

          tail->next = new_node;
          tail = new_node;
          }

          // print the list:
          for (node_t *current_node = head; current_node; current_node = current_node->next)
          printf("%d ", current_node->value);
          putchar('n');


          clean_up:
          fclose(input_file);

          for (node_t *current_node = head, *temp; current_node; current_node = temp) {
          temp = current_node->next;
          free(current_node);
          }

          return result;
          }


          Ideally you'd write functions to manage the list:



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

          typedef struct node_tag {
          int value;
          struct node_tag *next;
          } node_t;

          typedef struct list_tag {
          node_t *head;
          node_t *tail;
          } list_t;

          void list_create(list_t *list)
          {
          list->head = list->tail = NULL;
          }

          bool list_push_back(list_t *list, int value)
          {
          node_t *new_node = calloc(1, sizeof *new_node);
          if (!new_node)
          return false;

          new_node->value = value;

          if (!list->head) {
          list->head = list->tail = new_node;
          return true;
          }

          list->tail->next = new_node;
          list->tail = new_node;
          return true;
          }

          void list_print(list_t *list)
          {
          for (node_t *current_node = list->head; current_node; current_node = current_node->next)
          printf("%d ", current_node->value);
          }

          void list_free(list_t *list)
          {
          for (node_t *current_node = list->head, *temp; current_node; current_node = temp) {
          temp = current_node->next;
          free(current_node);
          }
          }

          bool read_int(FILE *input_file, int *value)
          {
          return fscanf(input_file, "%d", value) == 1;
          }

          int main(void)
          {
          char const *filename = "test.txt";
          FILE *input_file = fopen(filename, "r");
          if (!input_file) {
          fprintf(stderr, "Couldn't open "%s" for reading :(nn", filename);
          return EXIT_FAILURE;
          }

          // read from file and build a list:
          list_t list;
          list_create(&list);
          int value;

          while (read_int(input_file, &value)) {
          if (!list_push_back(&list, value)) {
          fputs("Not enough memory :(nn", stderr);
          // clean up:
          fclose(input_file);
          list_free(&list);
          return EXIT_FAILURE;
          }
          }

          // print the list:
          list_print(&list);
          putchar('n');

          // clean up:
          fclose(input_file);
          list_free(&list);
          }


          Output:



          1 3 4 2 4 3 1 4 4 2 1 3






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 5:51

























          answered Nov 14 '18 at 3:58









          SwordfishSwordfish

          9,37811436




          9,37811436

























              0














              When you hit a space character you iterate i. At the end of your loop you iterate i.



              So when you hit a space character you iterate i twice, skipping the number and landing on the next space character.



              Which is why you get the first number but miss the rest.



              edit: removed getline() comments due to feedback from @swordfish. Current implementation is not problematic.






              share|improve this answer






























                0














                When you hit a space character you iterate i. At the end of your loop you iterate i.



                So when you hit a space character you iterate i twice, skipping the number and landing on the next space character.



                Which is why you get the first number but miss the rest.



                edit: removed getline() comments due to feedback from @swordfish. Current implementation is not problematic.






                share|improve this answer




























                  0












                  0








                  0







                  When you hit a space character you iterate i. At the end of your loop you iterate i.



                  So when you hit a space character you iterate i twice, skipping the number and landing on the next space character.



                  Which is why you get the first number but miss the rest.



                  edit: removed getline() comments due to feedback from @swordfish. Current implementation is not problematic.






                  share|improve this answer















                  When you hit a space character you iterate i. At the end of your loop you iterate i.



                  So when you hit a space character you iterate i twice, skipping the number and landing on the next space character.



                  Which is why you get the first number but miss the rest.



                  edit: removed getline() comments due to feedback from @swordfish. Current implementation is not problematic.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 14 '18 at 4:20

























                  answered Nov 14 '18 at 3:57









                  lodlod

                  953612




                  953612






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292164%2fnot-reading-number-properly%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Xamarin.iOS Cant Deploy on Iphone

                      Glorious Revolution

                      Dulmage-Mendelsohn matrix decomposition in Python