簡體   English   中英

從文本文件讀取錯誤:分段錯誤(核心轉儲)

[英]Reading from text file error : Segmentation fault (core dumped)

我在文本文件中輸入了一個 (10*5) 矩陣和兩個變量值。 矩陣元素是制表符分隔的。 例如:

我想從文本文件和打印輸出中讀取矩陣和其他兩個變量值。

我必須使用valarray作為矩陣。

我嘗試了以下方式,但它顯示“分段錯誤(核心轉儲)”。

任何有關更正我的代碼的建議將不勝感激。 謝謝。

#include <fstream>
#include <iomanip>
#include <iostream>
#include <valarray>

using namespace std;
using matrix = valarray<valarray<double> >;

int main()
{
    matrix table{std::valarray<double>{0.0, 10}, 10}; //updated
    //matrix table;
    double a;
    int b;

    fstream inFile;
    inFile.open("tablenew1.txt", fstream::in);
    if (inFile.is_open()) {

        for (int i = 0; i < 10; ++i) {
            for (int j = 0; j < 5; ++j) {
                inFile >> table[i][j];
            }
        }
        inFile >> a;
        inFile >> b;
        inFile.close();
    }

    //printout

    for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 5; ++j) {
            std::cout << std::fixed;
            std::cout << std::setprecision(4);
            cout << table[i][j] << "\t";
        }
        cout << endl;
    }

    cout << a << '\n';
    cout << b << '\n';
    return 0;
}

更新

更新后的代碼顯示以下錯誤:free(): invalid pointer Aborted (core dumped)

改變

matrix table{std::valarray<double>{0.0, 10}, 10};

進入

matrix table(std::valarray<double>(0.0, 10), 10);

獲得正確的構造函數。

您現在獲得了其他構造函數之一(我認為可能是initializer_listindirect_array ctor)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM