我需要读取以这种方式构造的 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",
¤t_line.first_number,
¤t_line.second_number,
¤t_line.first_char,
¤t_line.second_char))
{
// Append.
lines_from_file.push_back(current_line);
}
}
关于c++ - 将txt文件读入c++中的多变量维度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12457358/