我有一個.csv文件,它只包含兩列具有人名和年齡的列。它看起來像:在C++中讀取csv文件
Name Age
Peter 16
George 15.5
Daniel 18.5
我只想收集在一個雙打載體的人的年齡。所以我想有一些像vect = {16,15.5,18.5}。
如何在僅使用標準庫時實現此目標?
非常感謝
我有一個.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);
}
你應該閱讀[這個](http://stackoverflow.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