c++ - 将txt文件读入c++中的多变量维度数组

标签 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], ',');
}

显然这只向您展示了我认为我可以使用的东西....但我愿意接受任何建议

提前感谢我的工程师

最佳答案

定义一个简单的 struct 来表示文件中的一行并使用 vector那些 struct 的。使用 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);
    }

}

关于c++ - 将txt文件读入c++中的多变量维度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12457358/

相关文章:

c++ - Qt 拆分 QString

c# - 编译器错误 : Invalid rank specifier: expected' ,' or ' ]' on Two Dimensional Array Initialization

php - 重新排列数组以合并重叠结果

node.js - 如何在 Angular 7 中创建使用 FS 模块列出目录中文件的服务?

c++ - STL 中的错误代码是否有任何异常?

c++ - WSAENOBUFS 和 WSAEWOULDBLOCK 有什么区别?

c++ - 如何在特定地址声明一个结构?

c - 如何在 C 中声明和初始化 4 维数组

c++ - 逐行读取文件并存储不同的变量

java - 如何访问Java数组中的第一列数据并分配给另一个变量?