实现用C++读取.csv文件,并存到STL中
.csv文件即将表格数据转换为用分隔字符分隔的值(也可以不是逗号)
#include
#include
#include
int main(){
vector<vector<int>> user_arr;
ifstream fp("xxx/user_data.csv"); //定义声明一个ifstream对象,指定文件路径
string line;
getline(fp,line); //跳过列名,第一行不做处理
while (getline(fp,line)){ //循环读取每行数据
vector<int> data_line;
string number;
istringstream readstr(line); //string数据流化
//将一行数据按','分割
for(int j = 0;j < 11;j++){ //可根据数据的实际情况取循环获取
getline(readstr,number,','); //循环读取数据
data_line.push_back(atoi(number.c_str())); //字符串传int
}
user_arr.push_back(data_line); //插入到vector中
}
return 0;
}
补充:
将字符串类型数据转换成 int 类型需要先使用 .c_str() 转成 const char* 类型,再用 atoi() 转成 int ,如果转为浮点型则 atof() ,long 型则 atol() 等等。
#include
#include
#include
#include
#include
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;
}
示例3 csv数据保存创建文件
#include
#include
#include
#include
#include
using namespace std;
void main()
{
ofstream outFile("Data.csv", ios::out);
//ios::out:如果没有文件,那么生成空文件;如果有文件,清空文件
if (!outFile)
{
cout << "打开文件失败!" << endl;
exit(1);
}
//写入3行数据
for (int i = 0; i < 3; i++)
{
outFile << 12 << ",";
outFile << 13 << ",";
outFile << 14 << ",";
outFile << "NaN" << endl;
}
outFile.close();
cout << "写入数据完成" << endl;
}
#include
#include
#include
#include
#include
#include
class CSVRow
{
public:
std::string const& operator[](std::size_t index) const
{
return m_data[index];
}
std::size_t size() const
{
return m_data.size();
}
void readNextRow(std::istream& str)
{
std::string line;
std::getline(str, line);
std::stringstream lineStream(line);
std::string cell;
m_data.clear();
while(std::getline(lineStream, cell, ','))
{
m_data.push_back(cell);
}
// This checks for a trailing comma with no data after it.
if (!lineStream && cell.empty())
{
// If there was a trailing comma then add an empty element.
m_data.push_back("");
}
}
private:
std::vector<std::string> m_data;
};
std::istream& operator>>(std::istream& str, CSVRow& data)
{
data.readNextRow(str);
return str;
}
int main()
{
std::ifstream file("plop.csv");
CSVRow row;
while(file >> row)
{
std::cout <<"4th Element(" << row[3] <<")
";
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)