简体   繁体   English

如何从 txt 文件中读取二维三角形数组?

[英]How to read a 2d triangle array from txt file?

I want to read 2d triangle array from a txt file.我想从 txt 文件中读取二维三角形数组。

1
8 4
2 6 9
8 5 9 6

I wrote this code.我写了这段代码。 At the end I wanted to print it out if I got the array right.最后,如果数组正确,我想将其打印出来。 When I run it it does not print the array, but in debug it prints.当我运行它时,它不会打印数组,但在调试时它会打印。 So there is a problem, but I cannot find it.所以有问题,但我找不到。 Sometimes it gives segmentation fault, but I dont understand.有时它会给出分段错误,但我不明白。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>


int main() {

    std::ifstream input_file("input_file.txt");

    int size{1};
    int **arr = (int**)malloc(3*sizeof(int));

    int *lineArr = (int*) malloc(size*sizeof(int));

    int temp{};

    int index{};

    while(input_file >> temp){
        lineArr[index] = temp;
        index++;
        if(index == size){
            index = 0;
            arr[size-1] = new int[size-1];
            for(int i{}; i<size; i++){
                arr[size-1][i] = lineArr[i];
            }
            size++;
            lineArr = (int*) realloc(lineArr, size*sizeof(int));
        }
    }

    input_file.close();

    for(int a{}; a<size-1; a++){
        for(int j{}; j<=a; j++){
            std::cout << arr[a][j] << " ";
        }
        std::cout << std::endl;
    }


    return 0;
}

You can just use vector instead of malloc.你可以只使用vector而不是malloc。 Like this:像这样:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>

using namespace std;

int main() {

    ifstream input_file("input_file.txt");
    vector<string> numbers;
    if (input_file.is_open()) {
        string line;
        while (getline(input_file, line)) {
           numbers.push_back(line);
        }
        input_file.close();
    }

    for (vector<string>::iterator t=numbers.begin(); t!=numbers.end(); ++t) 
    {
        cout<<*t<<endl;
    }

    return 0;
}

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

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