逐行从文本文件中读取字符串并将其存储在链接列表中

时间:2014-03-25 12:33:42

标签: c string linked-list stdin

我的程序只能读取文件的第一行然后终止。任何人都可以告诉我应该修改什么来读取文件中的所有行。

下面是我的read_line和插入函数:

/*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;
}

3 个答案:

答案 0 :(得分:2)

每次迭代都需要增加i

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;
}

答案 1 :(得分:1)

您可以将代码更新为

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.
}

答案 2 :(得分:0)

这是人们通常喜欢在循环中循环的原因之一,因为在while循环中,有时我们忘记修改计数器变量,有时我们忘记初始化变量。在for循环初始化中,条件测试和修改在同一个地方执行,因此我们通常在其中提交的错误将不会在for循环中执行,否则它们在for循环中没有任何其他优点。