在C++中读取csv文件
问题描述:
我有一个.csv文件,它只包含两列具有人名和年龄的列。它看起来像:在C++中读取csv文件
Name Age
Peter 16
George 15.5
Daniel 18.5
我只想收集在一个双打载体的人的年龄。所以我想有一些像vect = {16,15.5,18.5}。
如何在仅使用标准库时实现此目标?
非常感谢
答
你可以做这样的事情:
#include <sstream>
#include <string>
#include <fstream>
ifstream infile("yourfile.csv");
std::vector<double> ages;
while (infile)
{
std::string line;
if (!std::getline(infile, line,' ')) break;
std::istringstream iss(line);
string name;
double age;
if (!(iss >> name >> age)) { break; }
ages.push_back(age);
}
+1
你应该阅读[这个](http://*.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – NathanOliver
答
@BugsFree谢谢你的剧本,但它似乎并没有为我工作。
这是我如何做它最终(如果有人有兴趣...)
ifstream infile("myfile.csv");
vector<string> classData;
vector<double> ages;
std::string line;
while (getline(infile, line,'\n'))
{
classData.push_back(line); //Get each line of the file as a string
}
int s = classData.size();
for (unsigned int i=1; i<s; ++i){
std::size_t pos = classData[i].find(","); // position of the end of the name of each one in the respective string
ages[i-1] = std::stod(classData[i].substr(pos+1,classData[i].size())); // convert string age to a double
}
'我怎么能做到这一点?'应该用'你做了什么,所以far'来解决这个问题前面。 – sjsam
这看起来不像一个CSV文件,而是像一个固定格式的文件?第一场从偏移量0开始,第二场在偏移量10? – Elijan9