我编写了一个接受txt文件作为输入并进行解析的代码,并将其放入2d数组myarray [] [2]中。输入文件结构如下所示:
aaa/bbb
bbb/ccc
ccc/ddd
它应该这样解析:
myarray[0][0] = "aaa"
myarray[0][1] = "bbb"
myarray[1][0] = "bbb"
myarray[1][1] = "ccc"
我这样做的代码:
void Parse_File(string file){
ifstream inFile;
inFile.open(file);
if (inFile.is_open()){
inFile.clear();
int lines = count(istreambuf_iterator<char>(inFile), istreambuf_iterator<char>(), '\n');
string myarray[lines][2];
int mycount = 0;
do{
getline(inFile, input);
myarray[mycount][0] = input.substr(0, input.find("/"));
myarray[mycount][1] = input.substr(input.find("/") +1, input.length());
mycount++;
}while (input != "");
}else{
Fatal_Err("File Doesn't Exist");
}
inFile.close();
}
但是myarray在此功能之后没有任何内容。do-while语句不会循环。我不知道为什么。任何帮助表示赞赏。谢谢。
您的文件有几个问题,但主要的问题是:您忘记将文件读取指针带回到文本文档的开头。该count
函数将所述指针指向末尾,因此您需要将其移回。
因此,您需要使用该seekg()
函数将指针拖动到所需的位置。
看看下面的代码是否适合您
void Parse_File(string file)
{
ifstream inFile;
inFile.open(file);
if (inFile.is_open())
{
inFile.clear();
int lines = count(istreambuf_iterator<char>(inFile), istreambuf_iterator<char>(), '\n');
//Pitfall : By counting the lines, you have reached the end of the file.
inFile.seekg(0);// Pitfall solved: I have now taken the pointer back to the beginning of the file.
....
....//Rest of your code
}
}
另外,您需要学习调试,以便更轻松地理解代码。我会推荐Visual Studio代码来调试c ++。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句