0

我对 C++ 很陌生。我只想在“.csv”文件中获取某个字段,而不是全部删除。我很确定,它一定很容易,但我不知道该怎么做。这是我获取所有“.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;
}
4

2 回答 2

3

如果您可以使用boost库,那么boost::tokenizer将提供您需要的功能。最值得注意的是,它正确处理包含逗号的引用字段值。以下是从链接页面复制的代码片段:

// 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";
   }
}

您可以将每次ligne读取传递给 atokenizer并提取您需要的字段。

于 2012-10-30T08:56:33.357 回答
2

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)
}
于 2012-10-30T09:04:51.293 回答