我想用c ++读取csv文件 所以这是我的代码
int main(){
ifstream classFile("class.csv");
vector<string> classData;
while (getline(classFile, line,',')) // there is input overload classfile
{
classData.push_back(line);
}
}
这是我的问题:我的问题是它何时读取每一行的最后一列 (因为它没有用逗号分隔),它读取最后一列数据和下一行数据的第一列 例如,如果我的数据是
className,classLocation,教授 c ++,Library,John
然后它读起来像className / classLocation / Professor c ++ / Library / John
无论如何,我可以将我的最后一列与下一行的第一列分开吗? 谢谢,对不起,这令人困惑
答案 0 :(得分:17)
逐行阅读文件:
std::string line;
while(std::getline(stream, line)) ...
将每一行传递给istingstream并阅读字段:
std::istringstream s(line);
std::string field;
while (getline(s, field,',')) ...
<强>声明强>: 这是对csv文件的简化解析。
答案 1 :(得分:3)
对不起,我可以将一些简单的C推入这个帖子吗?
在那里阅读csv非常清楚:
#include <stdio.h>
int main()
{
float f1, f2;
FILE *fp;
fp = fopen("file.csv", "r");
while (fscanf(fp, "%g,%g\n", &f1, &f2) == 2)
printf("%g\n", f1+f2);
}
当然,它应该适用于C ++的工作原理。
在while
中,我们检查fscanf找到了多少个对象:fscanf(fp, "%g,%g\n", &f1, &f2) == 2
- fscanf返回它找到的对象数。
我希望它对某人有所帮助。
(如果有人希望在fscanf
上查看更多信息并阅读文件 - 请留下一些评论。)
答案 2 :(得分:0)
如果您有兴趣在void
部分中调用main
函数,请查看以下代码:
void readCSV(const string &strPath2Dataset)
{
ifstream csvFile;
string strPathCSVFile = strPath2Dataset + "/test.csv";
csvFile.open(strPathCSVFile.c_str());
if (!csvFile.is_open())
{
cout << "Path Wrong!!!!" << endl;
exit(EXIT_FAILURE);
}
vector<long double> timeStampIMU;
vector<long double> gyro_X;
vector<long double> gyro_Y;
vector<long double> gyro_Z;
vector<long double> acc_X;
vector<long double> acc_Y;
vector<long double> acc_Z;
string line;
vector <string> vec;
getline(csvFile, line); // skip the 1st line
while (getline(csvFile,line))
{
if (line.empty()) // skip empty lines:
{
//cout << "empty line!" << endl;
continue;
}
istringstream iss(line);
string lineStream;
string::size_type sz;
vector <long double> row;
while (getline(iss, lineStream, ','))
{
row.push_back(stold(lineStream,&sz)); // convert to double
}
timeStampIMU.push_back(row[0]);
gyro_X.push_back(row[1]);
gyro_Y.push_back(row[2]);
gyro_Z.push_back(row[3]);
acc_X.push_back(row[4]);
acc_Y.push_back(row[5]);
acc_Z.push_back(row[6]);
}
//cout << "size ts = " << timeStampIMU.size() << endl;
for (size_t i = 0; i < timeStampIMU.size(); i++)
{
cout << "ts_imu = " << setprecision(12) << timeStampIMU[i] << endl;
cout << "gx = " << setprecision(12) << gyro_X[i] << endl;
cout << "gy = " << setprecision(12) << gyro_Y[i] << endl;
cout << "gz = " << setprecision(12) << gyro_Z[i] << endl;
cout << "ax = " << setprecision(12) << acc_X[i] << endl;
cout << "ay = " << setprecision(12) << acc_Y[i] << endl;
cout << "az = " << setprecision(12) << acc_Z[i] << endl;
cout << "--------------------------------" << endl;
}
}
我的.csv
文件是从IMU传感器提供的数据集,用逗号分隔:
TimeStamp, Gyro_X, Gyro_Y, Gyro_Z, Acc_X, Acc_Y, Acc_Z