整数値のcsvなりtxtのファイル(カンマ区切りとかスペース区切り)を読みこませる方法を毎回ググってるので、二度としないようにメモ。
この例は、Zachary karate clubのデータを用いています。
reader.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
std::vector< std::vector< int > > A(100, std::vector<int>(2));
int main(){
std::ifstream ifs("karate.txt"); // ファイル読み込み
/*
1 2
1 3
2 3
…
*/
if(!ifs){
std::cout<<"Error!";
return 1;
}
std::string str;
int line = 0;
int i = 0;
int j = 0;
while(getline(ifs,str)){
std::string token;
std::istringstream stream(str);
while(getline(stream,token,' ')){ // スペース区切り
int temp = stoi(token); //文字列で読み込まれるため、整数へ変換
i = line / 2; // このデータ特有のもの
j = line % 2; // このデータ特有のもの
A[i][j] = temp; // 代入
std::cout << "A[" << i << "]""[" << j <<"] = " << temp << std::endl;
line++;
}
}
std::cout << line << std::endl;
for (int tmp_i = 0; tmp_i <= i; tmp_i++) {
for (int tmp_j = 0; tmp_j <= j; tmp_j++) {
std::cout << A[tmp_i][tmp_j] << " ";
}
std::cout << "" << std::endl;
}
return 0;
}
あくまで出力は、めっちゃしてます。
実際のデータだともっと処理は必要そうですね。