C++ 文字串處理 (CSV檔)
(1) 從CSV檔中將將文字一行一行的讀出
(2) 把文字以逗號分割後,存入陣列再取出,再依需要轉換格式,文字或數字
Data.CSV
111,222,333
aaa,bbb,ccc
1.2,2.2,3.3
======================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector> //陣列
using namespace std;
int main()
{
ifstream inFile("Data.csv", ios::in);
if (!inFile)
{
cout << "開啟檔案失敗!" << endl;
exit(1);
}
string line;
while (getline(inFile, line))//getline(inFile, line)表示按行讀取CSV檔案中的資料
{
cout << "org=" << line << endl;
}
}
=============================================================
用函數來處理分割字串
vector<string> _csv(string s)
{
vector<string> arr;
istringstream delim(s);
string token;
int c = 0;
while (getline(delim, token, ','))
{
arr.push_back(token);
c++;
}
return arr;
}
完整程式
-----------------------------------------
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector> //陣列
using namespace std;
vector<string> _csv(string s);
int main()
{
ifstream inFile("Data.csv", ios::in);
if (!inFile)
{
cout << "開啟檔案失敗!" << endl;
exit(1);
}
string line;
while (getline(inFile, line))
{
cout << "org=" << line << endl;
//========================
vector<string> a = _csv(line);
cout << "size=" << a.size() << endl;
for (int ii = 0; ii < a.size(); ii++)
{
cout << a[ii] << ",";
}
cout << endl;
//========================
}
}
vector<string> _csv(string s)
{
vector<string> arr;
istringstream delim(s);
string token;
int c = 0;
while (getline(delim, token, ','))
{
arr.push_back(token);
c++;
}
return arr;
}
沒有留言:
張貼留言