在c ++中将txt文件读入多变量维数组

时间:2012-09-17 10:25:11

标签: c++ multidimensional-array readfile

我需要读取以这种方式构建的txt文件

0,2,P,B
1,3,K,W
4,6,N,B
etc.

现在我需要读取像arr [X] [4]
这样的数组 问题是我不知道这个文件中的行数 另外我需要2个整数和2个字符...

我想我可以用这个代码示例来阅读它

ifstream f("file.txt");
while(f.good()) {
  getline(f, bu[a], ',');
}
很明显,这只能告诉你我认为我可以使用的内容......但是我愿意接受任何建议

提前thx并为我的英雄呀

1 个答案:

答案 0 :(得分:5)

定义一个简单的struct来表示文件中的一行,并使用structvector。使用vector可以避免必须明确管理动态分配,并且会根据需要增长。

例如:

struct my_line
{
    int first_number;
    int second_number;
    char first_char;
    char second_char;

    // Default copy constructor and assignment operator
    // are correct.
};

std::vector<my_line> lines_from_file;

完整读取行,然后拆分它们,因为发布的代码允许在一行上有5个逗号分隔的字段,例如,当只需要4个时:

std::string line;
while (std::getline(f, line))
{
    // Process 'line' and construct a new 'my_line' instance
    // if 'line' was in a valid format.
    struct my_line current_line;

    // There are several options for reading formatted text:
    //  - std::sscanf()
    //  - boost::split()
    //  - istringstream
    //
    if (4 == std::sscanf(line.c_str(),
                         "%d,%d,%c,%c",
                         &current_line.first_number,
                         &current_line.second_number,
                         &current_line.first_char,
                         &current_line.second_char))
    {
        // Append.
        lines_from_file.push_back(current_line);
    }

}
相关问题