1
1

More than 3 years have passed since last update.

CSVファイルでPythonからC++への行列データの受け渡し

Last updated at Posted at 2021-03-17

はじめに

Pythonで計算した結果の4×3の行列を,C++から読みたいと思い、その方法をまとめました。

書き込み(Python)

write.py
import csv

data = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

with open('test.csv', 'w') as file:
    writer = csv.writer(file, lineterminator='\n')
    writer.writerows(data)

読み込み(Python)

read.py
import csv
import pprint

with open('test.csv') as f:
    reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
    l_f = [row for row in reader]

print(l_f) 

読み込み(C++)

read.cpp
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <iostream>

std::vector<std::string> split(std::string& input, char delimiter)
{
  std::istringstream stream(input);
  std::string field;
  std::vector<std::string> result;
  while (getline(stream, field, delimiter)) {
    result.push_back(field);
  }
  return result;
}

int main(){

  std::string file("test.csv");

  std::ifstream ifs(file);

  std::string line;
  std::vector<std::string> strvec = split(line, ',');

  float m11,m12,m13,m14;
  float m21,m22,m23,m24;
  float m31,m32,m33,m34;

  getline(ifs, line);
  strvec = split(line, ',');
  m11 = std::stof(strvec.at(0));
  m12 = std::stof(strvec.at(1));
  m13 = std::stof(strvec.at(2));
  m14 = std::stof(strvec.at(3));

  getline(ifs, line);
  strvec = split(line, ',');
  m21 = std::stof(strvec.at(0));
  m22 = std::stof(strvec.at(1));
  m23 = std::stof(strvec.at(2));
  m24 = std::stof(strvec.at(3));

  getline(ifs, line);
  strvec = split(line, ',');
  m31 = std::stof(strvec.at(0));
  m32 = std::stof(strvec.at(1));
  m33 = std::stof(strvec.at(2));
  m34 = std::stof(strvec.at(3));

  std::cout << m11 << " " << m12 << " " << m13 << " " << m14 << std::endl;
  std::cout << m21 << " " << m22 << " " << m23 << " " << m24 << std::endl;
  std::cout << m31 << " " << m32 << " " << m33 << " " << m34 << std::endl;

return 0;
}

1
1
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
1
1