目錄
1.檔案流指針(輸入輸出)
方法1:substr截取字元串
方法2:boost::split()截取字元串
1.檔案流指針(輸入輸出)
【C++】C++ 檔案讀寫 ofstream和ifstream詳細用法 - bdy - 部落格園 (cnblogs.com)
方法1:substr截取字元串
#define FILENAME "C:\\Users\\xiao_\\Desktop\\text.csv"
#define FILENAME1 "C:\\Users\\xiao_\\Desktop\\text1.csv"
int main()
{
std::list<std::string> StatYearList;
//從test.txt檔案讀取資料
std::ifstream fin(FILENAME , std::ios::in);
if (!fin.is_open())
{
fmt::print( "error open file![{0}]\n", FILENAME);
return -1;
}
while (!fin.eof())
{
std::string tmp;
std::string data;
IemsStatYear statYear;
getline(fin, tmp);
size_t star = tmp.find(',', 0);
if (star == std::string::npos)
{
fmt::print("找不到字元串[{0}]\n", star);
}
statYear.year = stoi(tmp.substr(0, star));
star++;
statYear.devName = tmp.substr(star, tmp.find(',', star));
star++;
statYear.devType = tmp.substr(star, tmp.find(',', star));
star++;
statYearList.push_back(statYear);
}
fin.close();
//輸出到另一個檔案test0.txt
ofstream out(FILENAME1 , ios::out);
out << "NAME,DATA_TYPE,DATA_MONTH,DATA_DAY,VAL,UNIT" << endl;
for (int i = 0; i < statYearList.size(); i++)
{
out << statYearList[i].NAME << "," << statYearList[i].DATA_TYPE << "," <<
statYearList[i].DATA_MONTH << "," << statYearList[i].DATA_DAY << "," <<
statYearList[i].VAL << "," << statYearList[i].UNIT << endl;
}
out.close()
return 0;
}
方法2:boost::split()截取字元串
用法:
#include <boost/algorithm/string.hpp>
std::string line("a fox jump ");
// trim(), trim_left(), trim_right()
boost::trim(line); // line: "a fox jump"
std::vector<std::string> contents;
// 分割,通過boost::is_any_of指定分割符。
boost::split(contents, line, boost::is_any_of(", "));
// 拼接
std::string line2 = boost::join(contents, "="); //line2: a=fox=jump
舉例:
int main()
{
std::ifstream fin(fileName, std::ios::in);
if (!fin.is_open())
{
fmt::print( "error open file![{0}]\n", fileName);
return -1;
}
while (!fin.eof())
{
TYPE_iems_stat_year statYear;
std::string tmp;
getline(fin, tmp);
std::vector<std::string> contents;
boost::split(contents,tmp,boost::is_any_of(","));
if(contents[0] == "")
{
return 0;
}
if(contents[0] == "year")
{
continue;
}
std::string sqlCmd = fmt::format("insert into iems_stat_year values ({},\" {}\",\"{}\",\"{}\",\"{}\",{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{})",
contents[0],contents[1],contents[2],contents[3],contents[4],contents[17],contents[5],contents[6],contents[7],contents[8],contents[9],
contents[10],contents[11],contents[12],contents[13],contents[14],contents[15],contents[16],contents[18],contents[19],contents[20],contents[21]);
StatYearList.push_back(sqlCmd);
}
fin.close();
return 0;
}