c++ - 读取 txt 文件并将值放入列表中 (c++)

标签 c++ list file linked-list

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

没有错误,但如果我想执行它,我会得到一个崩溃报告。 一开始我忽略了请求的格式。

最佳答案

您的代码中有几个错误。我将列出几个明显的供您考虑:

  1. 你如何处理?您在显示列表时忽略了头部,但它实际上包含第一个值。
  2. 每次尝试使用node->next时,都应保证该节点不为NULL
  3. 正如第一个答案所指出的,在 while 循环之后,temp 为 NULL。解决方案可能while (temp->next)
  4. 列表的析构函数不正确,您将遇到空列表的段错误
  5. 您使用 printffgets 而不是 iostream,并且您使用了两个类。你更喜欢哪一种,C 还是 C++?选择一个你喜欢的。

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

相关文章:

C++ 这个类型应该满足 std::is_copy_assignable 吗?

c++ - 我正在使用 tcp 进行很多小的发送,我应该关闭 Nagles 算法吗? (人们也将其称为 TCP_NODELAY)

c++ - 在单个列表中存储多个派生类类型

c - 只获取c/Ubuntu中某个目录下的文件

python - 使用前 8 个字符重命名目录中的文件并保留文件扩展名 (Python)

c++ - 如何避免 ncurses 中的 stdscr 重叠?

c++ - Visual C++ 不会自动完成类成员

java - Scala:将二维列表转换为一维

python - 在整数数组/列表中查找重复项

perl - 将数据重定向到文件时出错