[英]How to get part of an .csv file in C++?
I am pretty new to C++. 我对C ++很陌生。 I just want to get a certain field on a ".csv" file, not all off it. 我只想在“ .csv”文件上获取某个字段,而不是全部关闭。 I am pretty sure, it must be very easy, but I don't know how to do it. 我很确定,这一定很容易,但是我不知道该怎么做。 Here is my code to get all the ".csv" content : 这是获取所有“ .csv”内容的代码:
#include <iostream>
#include <fstream>
#include <string>
// #include "Patient.h"
using namespace std;
int main()
{
// CPatient patient;
ifstream file("C:/Users/Alex/Desktop/STAGE/test.csv");
if(file)
{
// the file did open well
string line;
while(getline(file, line, ';')) //Until we did not reach the end we read
{
cout << line << endl; //Console Result
}
}
else
{
cout << "ERROR: Could not open this file." << endl;
}
system("PAUSE");
return 0;
}
If you can use boost
libraries, then boost::tokenizer
would provide the functionality you require. 如果可以使用boost
库,则boost::tokenizer
将提供您所需的功能。 Most notablty, it correctly handles quoted field values that contain commas. 最明显的是,它可以正确处理包含逗号的带引号的字段值。 The following is a code snippet copied from the linked page: 以下是从链接页面复制的代码段:
// simple_example_2.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
int main(){
using namespace std;
using namespace boost;
string s = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
tokenizer<escaped_list_separator<char> > tok(s);
for(tokenizer<escaped_list_separator<char> >::iterator beg=tok.begin();
beg!=tok.end();
++beg)
{
cout << *beg << "\n";
}
}
You could pass each ligne
read to a tokenizer
and extract the fields you require. 您可以将每个ligne
读取传递给tokenizer
然后提取所需的字段。
Try reading whole lines and split them afterwards: 尝试阅读整行,然后将其拆分:
int N = 5; // search the fifth field
char separator = ';';
while (std::getline(fichier, ligne)) {
// search for the Nth field
std::string::size_type pos = 0;
for (int i = 1; i < N; ++i)
pos = ligne.find_first_of(separator, pos) + 1;
std::string::size_type end = ligne.find_first_of(separator, pos);
// field is between [pos, end)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.