Fed*_*d03 0 c++ multidimensional-array readfile
我需要读取以这种方式构造的txt文件
0,2,P,B
1,3,K,W
4,6,N,B
etc.
Run Code Online (Sandbox Code Playgroud)
现在我需要读取像arr [X] [4]这样的数组
.问题是我不知道这个文件中的行数.
另外我需要2个整数和2个字符...
我想我可以用这个代码示例阅读它
ifstream f("file.txt");
while(f.good()) {
getline(f, bu[a], ',');
}
Run Code Online (Sandbox Code Playgroud)
很明显,这只会告诉你我认为我可以使用的......但我对任何建议持开放态度
提前thx和我的eng
定义一个简单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;
Run Code Online (Sandbox Code Playgroud)
完整读取行,然后拆分它们,因为发布的代码允许在一行上有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);
}
}
Run Code Online (Sandbox Code Playgroud)