Question

My program can only read the first line of the file and then terminated. Can anyone tell me what should I modify in order to read all the lines from the file.

Below is my read_line and insert functions:

/*read_line:*/
#include <stdio.h>
#include "readline.h"

int read_line(char str[],int n)
{
    int ch,i=0;
    while((ch = getchar()) != '\n' && ch != EOF){
    if(i < n)
       str[i] = ch;
    continue;
}
    str[i]= '\0';
    return i;
}

/*insert:*/
struct part *insert(struct part *inventory)
{
    struct part *student;
    student = malloc(sizeof(struct part)+1);
    read_line(student -> name, NAME_LEN);
    student ->next = inventory;
    return student;
}

//Input file:
//B1212122 Jack Kevin 91
//B121213i Lee Van 82

//My output only contains "B1212122 Jack Kevin 91".
And my main program:
#include <stdio.h>
#include <stdlib.h>
#include "readline.c"
#define NAME_LEN 80

struct part{
    char name[NAME_LEN+1];
    struct part *next;
};

struct part *insert(struct part *inventory);
void print(struct part *inventory);
void print_inventory(struct part *student);
int main(void)
{
    struct part *inventory = NULL;
    inventory = insert(inventory);
    print(inventory);
    return 0;
}
Was it helpful?

Solution

You need to increase i each iteration:

int read_line(char str[],int n)
{
    int ch,i=0;
    while((ch = getchar()) != '\n' && ch != EOF){
        if(i < n)
           str[i] = ch;
        i++;                  // Change here
    }
    str[i]= '\0';
    return i;
}

OTHER TIPS

You can update code to

int read_line(char str[],int n)
{
    int ch,i=0;
    while((ch = getchar()) != '\n' && ch != EOF){
    if(i < n)
       str[i++] = ch;
    continue;
    }
    str[i]= '\0';
    return i;
}

struct part *insert(struct part *inventory)
{
    struct part *student, *first=NULL;
    int i=0;
    //do the reading in loop, assuming you want to read multiple lines
    //as multiple student records.
    do {
        student = malloc(sizeof(struct part)+1);
        i= read_line(student -> name, NAME_LEN);
        if(i>0)
        {
           student ->next = inventory;
           if(!first)
               first = student;
        }
    }while(i>0);    

    return first; //assuming you want to return first instance of record added.
}

That is one of the reason when people generally prefer for loop over while loop because in while loop some time we forget to modify the counter variable and some time we forget to initialize variables. In for loop initialization, condition test and modification performed in the same place so the error that we generally commit in while will not perform in for loop else their is no any other advantages of for loop over while loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top