0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CSV形式の行列を読み込むプログラム(C++)

Last updated at Posted at 2023-01-09

プログラムについて

https://qiita.com/persim/items/87f4812fe8bf0ab90d00
上の記事で作成したCSV形式の行列をC++で読み込む必要があったため,読み込むためのプログラムを作成しました.

環境

  • MacBook Air(M1, 2020)
  • Docker(Ubuntu 20.04.5 LTS)
  • g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0

プログラム

readMatrix.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

int main(int argc, char* argv[])
{
    const std::string inputFile = argv[1];
    std::ifstream ifs(inputFile, std::ios::in);

    std::string buf;
// ファイルの各行から文字列を取得する
    getline(ifs, buf);  

// 1行目のコメントに関する処理
    std::istringstream sstream(buf);
    std::string s;
    int count = 0;

    int N, max_nonzero, nonzero;
// コメントから行列の大きさ,非零要素数の最大値,非零要素数の取得
    while (std::getline(sstream, s, ',')) {
        if (count == 0){
            N = std::stoi(s.substr(2));
            count++;
        } else if (count == 1){
            max_nonzero = std::stoi(s);
            count++;
        } else if (count == 2){
            nonzero = std::stoi(s);
        }
    }
    // std::cout << N << std::endl;
    // std::cout << max_nonzero << std::endl;
    // std::cout << nonzero << std::endl;
    
    double a[N][N];
// ファイルから行列データを取得する
    for(int i = 0; i < N; i++){
        getline(ifs, buf);
        std::istringstream sstream2(buf);
        std::string s2;
        for(int j = 0; j < N; j++){
            std::getline(sstream2, s2, ',');
            a[i][j] = std::stod(s2);
        }
    }
// 行列の各要素を1倍して計算している
    for(int i = 0; i < N; i++){
        for(int j = 0; j < N; j++){
            a[i][j] *= 1;
            std::cout << a[i][j] << std::endl;
        }
    }
}

実行方法

g++ readMatrix.cpp -o read
./read filename

実行結果

ターミナルに出力された値と,行列ファイルの値が一致しているので問題ないはず.

$ g++ readMatrix.cpp -o read
$ ./read 3_3matrix20230109141857.csv 
0.28367,0.750385,0
0.935173,0.379778,0.487891
0.368338,0.189218,0.754602

$ cat 3_3matrix20230109141857.csv 
# 3,3,1
2.836696849382646102e-01,7.503854470601402094e-01,0.000000000000000000e+00
9.351732236040680712e-01,3.797781741383208232e-01,4.878913783131487714e-01
3.683378046364506053e-01,1.892181686700632470e-01,7.546015295953415469e-01
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?