首页 > 解决方案 > c函数从txt文件中逐字符读取,将其转换为int并将其存储在链表中

问题描述

我想从 .txt 文件中逐个字符地读取数字序列,直到找到一个 \n 字符,这就是,直到找到一个输入。然后将这些数字中的每一个转换为整数,并制作一个链表来存储这些整数。位数是未定义的,它可以是 1 或 1 000 000。这是我到目前为止所做的,但我只是不知道如何将它们转换为整数,如何制作实际列表和然后打印它。

void make_seq_list ()
    {
        struct seq_node *seq_current = seq_head;

        int digit_;

        printf("sequence:\n");

        while ( (digit_ = fgetc("fptr")) != '\n')
        {
            //???
        }
    }

这就是我为这个列表定义每个节点的方式:

typedef struct seq_node //declaration of nodes for digit sequence list
{
    int digit; //digit already as an int, not char as read from the file
    struct seq_node *next;
} seq_node_t;

请注意,在 txt 文件中,序列类似于:

1 2 3 1 //it can go on indefinitely
/*something else*/

提前致谢。

标签: cfilelinked-list

解决方案


digit_ = fgetc("fptr")

这是完全错误的。函数声明fgetc

 int fgetc(FILE *stream);

所以,如果你想读取文件的上下文,你必须先打开它:

FILE * fptr = fopen("filename", "r"); // filename: input.txt for example.
if(!fptr) {
   // handle the error.
}

// now, you can read the digits from the file.
int c = fgetc(fp); 

如果您的文件只包含数字(从09),您可以使用fgetc逐位读取。伪代码:

    FILE * fptr = fopen("input.txt", "r");
    if(!fptr) {
       // handle the error.
    }
     while(1) {
        int c = fgetc(fp);
        if(isdigit(c)) {
            int digit = c-'0';
            // add "digit" to linked list
        } else if (c == '\n') { // quit the loop if you meet the enter character
            printf("end of line\n");
            break;
        } else if(c == ' ') { // this line is optional
            printf("space character\n");
        }
    }

    // print the linked list.

对于插入或打印链表,您可以在 google 中搜索。将为您提供大量示例。例如插入和打印链表的例子


推荐阅读