【问题标题】:C++ ifstream split w.r.t. a characterC++ ifstream 拆分 w.r.t.一个角色
【发布时间】:2012-10-05 15:45:43
【问题描述】:

我想 C++ 逐行读取文件,并将每一行 w.r.t 拆分为 "\t" 字符以填充矩阵。我的代码会这样

    ifstream data_x;
        double** test_data = new double*[100];
        for(int j = 0 ; j <  ; j++)
             test_data[j] = new double[4]; 

    data_x.open("X.txt");

    int i = 0;
    if (data_x.is_open()) 
    {
        while (!data_x.eof()) 
        {
            char** split = data_x.split("\t") 
            for(int k = 1 ; k < 4 ; k++)
                 test_data[i][k];
            i++;
        }
    }

    data_x.close();

    ifstream data_y;
    data_y.open("Y.txt");

    i = 0;
    if (data_y.is_open()) 
    {
        while (!data_y.eof()) 
        {
            data_y >> test_data[i][0];
            i++;
        }
    }

    data_y.close(); 

语法

 char** split = data_x.split("\t") 
 for(int k = 1 ; k < 4 ; k++)
      test_data[i][k];

是近似的。如何用 C++ 正确地做到这一点?

谢谢

【问题讨论】:

  • 使用 std::string、getline 和字符串库函数。
  • 首先使用std::string,然后使用boost字符串算法库分割每一行。
  • 每当我看到while (!data_x.eof()) 我可以保证下面的代码是错误的。 (这样可以正确完成,但是有很多更简洁的习语,所以知道的人不要在测试中使用 eof() )。
  • Splitting a string in C++的可能重复

标签: c++ split char iostream ifstream


【解决方案1】:

假设您的文件只包含数字,这是标准的 C++ 习语:

#include <vector>
#include <string>
#include <sstream>
#include <fstream>

std::ifstream infile("data.txt");

std::vector<std::vector<double>> matrix;

for (std::string line; std::getline(infile, line); )
{
     std::istringstream iss(line);
     std::vector<double> row;

     for (double d; iss >> d; )
     {
         row.push_back(d);
     }

     matrix.push_back(row);
}

如果您知道矩阵的大小,则可以添加相关的reserve 调用以避免向量重新分配。您还可以添加测试以检查一行上是否有任何无法识别的数据,但现在这应该可以帮助您入门。

【讨论】:

  • 我希望 C++11 中的新 Move 功能正确地涵盖了这一点。
【解决方案2】:

用空格分隔的实体创建向量实际上很简单:

std::vector<T> fields(
    std::istream_iterator<T>(
        d::istringstream(line) >> std::skipws),
    std:.istream_iterator<T>()));

如果您的单元格类型 T 会将除 '\t' 之外的其他空格视为分隔符,您可能希望使用修改后的 std::ctype&lt;char&gt; 构面来更改被视为空格的内容。

显然,上面的逻辑可以打包成一些更容易使用的函数。

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 2016-08-05
    • 2011-03-20
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多