[英]Read a txt file into a multi variable dimension array in c++
我需要讀取以這種方式構造的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
以表示文件中的一行,並使用這些struct
的vector
。 使用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;
閱讀完整的行,然后將它們拆分為已發布的代碼,例如,當只需要4個行時,該行將允許5個逗號分隔的字段:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.