定义一个简单struct
的来表示文件中的一行并使用其中vector
的一个struct
。使用 avector
可以避免显式管理动态分配,并且会根据需要增长。
例如:
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;
Read the lines in full and then split them as the posted code would allow 5 comma separated fields on a line for example, when only 4 is expected:
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);
}
}