【问题标题】:c function to read character by character from a txt file, make it into int and store it in a linked listc函数从txt文件中逐字符读取,将其转换为int并将其存储在链表中
【发布时间】:2020-09-01 01:57:27
【问题描述】:

我想从 .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*/

提前致谢。

【问题讨论】:

  • fgetc("fptr")是完全错误的,没有任何意义。阅读文档。其余的你需要想出一些代码。我确定相关信息在您的讲义中。否则谷歌“链表C”你应该偶然发现一些东西,有很多教程。另请阅读:How to Ask
  • 这可能会让您入门:stackoverflow.com/questions/4600797/…

标签: c file linked-list


【解决方案1】:
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搜索。将为您提供大量示例。比如example of inserting and printing linked-list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-25
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多