# C++
使用C++写入数据或者读取表格数据然后转化为vector<vector<string>>
,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| #include <iostream> #include <string> #include <vector> #include <fstream> #include <sstream> using namespace std; int main() { ofstream outFile; outFile.open("data.csv", ios::out); outFile << "name" << ',' << "age" << ',' << "hobby" << endl; outFile << "Mike" << ',' << 18 << ',' << "paiting" << endl; outFile << "Tom" << ',' << 25 << ',' << "football" << endl; outFile << "Jack" << ',' << 21 << ',' << "music" << endl; outFile.close(); ifstream inFile("data.csv", ios::in); string lineStr; vector<vector<string>> strArray; while (getline(inFile, lineStr)) { cout << lineStr << endl; stringstream ss(lineStr); string str; vector<string> lineArray; while (getline(ss, str, ',')) lineArray.push_back(str); strArray.push_back(lineArray); } getchar(); return 0; }
|
最后读取的结果保存在strArray
里面。
注意,该方法通过分辨,
来进行分割,所以说处理字符串类型的数据的时候注意不应该包含,
另外,一件比较有趣的事情:我现在才知道循环中定义的变量会在循环结束后自动垃圾回收🧐