txt文件中的值采用以下格式:

4
2 3
5 6
3 7
6 9


输出必须如下所示:

[2:3][5:6][3:7][6:9]


这是我的代码:

#include <iostream>
#include <stdio.h>
using namespace std;

class node {
    public:
        int info;
        node* next;
        node(){
            next = NULL;
        }
        node (int value){
            info = value;
            next = NULL;
        }
};

class list {
    private:
        node* head;
    public:
        list() {            //Constructor
            head = NULL;
        }

    void insert(int value){
        if (head == NULL){
            head = new node;
            head -> info = value;
            return;
        }
        node *temp = head;
        while (temp) {
            temp = temp -> next;
        }
        temp -> next = new node;
        temp -> info = value;
    }

    void showlist(){
        node* temp = head;
        temp = temp -> next;        //ignore first number in txt file
        cout << "Liste \n" << endl;
        while (temp){
            printf ("%d", temp -> info);
            //cout << temp -> info << endl;
            temp = temp -> next;
        }
    }

    ~list() {           //Destructor
        node* temp = head;
        while (head -> next != NULL) {
            delete temp -> next;
            temp -> next = NULL;
            temp = temp -> next;
        }
        delete head -> next;
        head -> next = NULL;
    }
};

int main(int argc, const char * argv[]) {
    list stone;

    FILE* fp;

    if (argc > 1)
        fp = fopen(argv[1], "r");
    else
        fp = fopen("output.txt", "r");

    if (!fp)
        printf("Can't open file \n");
    else {
        int value, state;
        int i = 0;
        do {
            state = fscanf(fp, "%d", &value);
            if (state != EOF){
                stone.insert(value);
            }
        stone.showlist();
        }
        while (state != EOF);
        fclose (fp);
    }

    return 0;
}


没有错误,但如果要执行,则会收到崩溃报告。
我一开始就忽略了要求的格式。

最佳答案

insert中的此块看起来不正确:

    while (temp) {
        temp = temp -> next;
    }
    temp -> next = new node;


while循环后,tempNULL,因此您不能调用temp -> next

关于c++ - 读取txt文件并将值放在列表中(C++),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16884043/

10-10 15:38