简体   繁体   English

c function 从 txt 文件中逐字符读取,将其转换为 int 并存储在链表中

[英]c function to read character by character from a txt file, make it into int and store it in a linked list

I want to read a sequence of digits, character by character, from a.txt file until I find a \n character, this is, until I find an enter.我想从 a.txt 文件中逐个字符地读取数字序列,直到找到一个 \n 字符,这就是,直到找到一个输入。 Then to transform each of those digits into integers, and make a linked list to store those integers.然后将这些数字中的每一个转换为整数,并制作一个链表来存储这些整数。 The number of digits is undefined, it can either be 1 or 1 000 000. This is what I have done so far, but I just can't get my head around on how to transform them into ints, how make the actual list and then print it.位数是未定义的,它可以是 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')
        {
            //???
        }
    }

This is how I defined each node for this list:这就是我为这个列表定义每个节点的方式:

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;

Note that in the txt file, the sequence is something like:请注意,在 txt 文件中,序列类似于:

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

Thanks in advance.提前致谢。

digit_ = fgetc("fptr")

It's totally wrong.这是完全错误的。 The declaration of fgetc function: fgetc function的声明:

 int fgetc(FILE *stream);

So, if you want to read the context of the file, you have to open it first:所以,如果你想读取文件的上下文,你必须先打开它:

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

If your file contents only the digits (from 0 to 9 ), you can use fgetc to read digit by digit.如果您的文件仅包含数字(从09 ),您可以使用fgetc逐位读取。 The peusedo-code:伪代码:

    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.

For inserting or printing the linked list, you can search in google.对于插入或打印链表,您可以在 google 中搜索。 There will be a ton of examples for you.将为您提供大量示例。 For example, example of inserting and printing linked-list例如插入和打印链表的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM