【问题标题】:Why I cannot read all characters from a file in C++ using std::vector<char>为什么我不能使用 std::vector<char> 从 C++ 文件中读取所有字符
【发布时间】:2013-08-22 05:01:20
【问题描述】:

我想用 c++ 读取一个大的 CSV 文件,但是逐行读取对我来说太慢了(大约 5M 记录)。由于我不确定文件(或空格)中的分隔符,我按字符读取文件,转换为字符串,拆分所有值并通过转换后的值填充数组为双精度值。我的代码如下所示,但它无法读取 '\n' 和 ' ' 字符?请您帮助我如何阅读它们。如果有任何更快,更可靠的阅读方式。

bool readPtFast(istream *dataIn, ANNpointArray &p) // read point (false on EOF)
{
    std::istream_iterator<char> begin(*dataIn), end;
    std::vector<char> in(begin, end);
    std::string wholeFileString(in.begin(), in.end()); // Not all chars are read!!


    std::vector<std::string> split_values_string;
    std::vector<double> split_values_double;

    boost::split(split_values_string, wholeFileString, boost::is_any_of("\n\r,;\t "));
    if (split_values_string.size()!=NRecords*NDims) {
        cerr << "Error reading file. I expected " << NRecords*NDims << " values, but I found " << split_values_string.size() << "records.\a";
        getchar();
        return false;
    }


    std::transform(split_values_string.begin(), split_values_string.end(), 
        std::back_inserter(split_values_double), 
        boost::lexical_cast<double, std::string>);

    std::copy(split_values_double.begin(),split_values_double.end(),*p);

    return true;
}

【问题讨论】:

  • 您可以通过使用istreambuf_iterator&lt;char&gt; 而不是istream_iterator&lt;char&gt; 来丢弃大量不需要的(从外观上看)处理。前者只会折腾检查并流式传输您的字符。我们在这里谈论的文件有多大?我看到了 500 万条记录;这是否意味着 5M doubles 或 5M rows ??
  • 我会使用istream &amp;,而不是指针。它更易于使用。

标签: c++ file csv


【解决方案1】:

默认情况下,std::istream_iterator 将跳过空格。也许您可以使用操纵器 std::noskipws,如下所述:http://www.cplusplus.com/reference/ios/noskipws/stream.unsetf(std::skipws) 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2023-04-05
    • 2014-10-24
    • 1970-01-01
    相关资源
    最近更新 更多