用C ++格式化CSV文件

时间:2014-02-07 22:09:06

标签: c++ csv

我正在尝试获取一个简单的CSV文件,逐行拆分,然后将其打印到控制台。目前我在编译时遇到错误,想知道我是否遗漏了一些明显的东西。

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

int main(int argc , char** argv) {

    std::string line;
    std::ifstream infile(argv[1]);

    if (infile) {

        while (getline(infile, line)) {

            std::istringstream ss(line);
            std::string token;

            while(std::getline(ss, token, ",")) {

                std::cout << token << "\n";

            }

        }

    }

    infile.close();
    return 0;

}

我得到的错误如下。

csv.cpp: In function 'int main(int, char**)':
csv.cpp:41:46: error: no matching function for call to 'getline(std::istringstream&,
std::string&, const char [2])'
csv.cpp:41:46: note: candidates are:
In file included from /usr/include/c++/4.7/string:55:0,
             from /usr/include/c++/4.7/bits/locale_classes.h:42,
             from /usr/include/c++/4.7/bits/ios_base.h:43,
             from /usr/include/c++/4.7/ios:43,
             from /usr/include/c++/4.7/istream:40,
             from /usr/include/c++/4.7/fstream:40,
             from csv.cpp:21:
/usr/include/c++/4.7/bits/basic_string.tcc:1070:5: note: template<class _CharT, class _Traits, class _Alloc> std::basic_istream<_CharT, _Traits>& std::getline(std::basic_istream<_CharT, _Traits>&, std::basic_string<_CharT, _Traits, _Alloc>&, _CharT)
/usr/include/c++/4.7/bits/basic_string.tcc:1070:5: note:   template argument deduction/substitution failed:
csv.cpp:41:46: note:   deduced conflicting types for parameter '_CharT' ('char' and 'const char*')
In file included from /usr/include/c++/4.7/string:54:0,
             from /usr/include/c++/4.7/bits/locale_classes.h:42,
             from /usr/include/c++/4.7/bits/ios_base.h:43,
             from /usr/include/c++/4.7/ios:43,
             from /usr/include/c++/4.7/istream:40,
             from /usr/include/c++/4.7/fstream:40,
             from csv.cpp:21:
/usr/include/c++/4.7/bits/basic_string.h:2792:5: note: template<class _CharT, class _Traits, class _Alloc> std::basic_istream<_CharT, _Traits>& std::getline(std::basic_istream<_CharT, _Traits>&, std::basic_string<_CharT, _Traits, _Alloc>&)
/usr/include/c++/4.7/bits/basic_string.h:2792:5: note:   template argument deduction/substitution failed:
csv.cpp:41:46: note:   candidate expects 2 arguments, 3 provided

2 个答案:

答案 0 :(得分:3)

getline的第三个参数是char,而不是char*。设为getline(ss, token, ',') - 请注明单引号。

哦,请注意CSV字段"like"",""this"(如果您想知道,这是一个值为like","this的单个字段)。 CSV语法还远远超出了人们的视线。

答案 1 :(得分:0)

也许你应该使用一个库进行CSV修改......或许this question很有用。