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読み取りをに渡しtokenizer、必要なフィールドを抽出できます。

于 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 に答える