对于此任务,我将打开一个文本文件,尝试将第1行和第3行读入名为front的数组中(分别在索引0和1处),然后将第2行和第4行读入名为back的数组中(在索引0和1处)分别),但还不够。什么都没有输入到数组,我的循环逻辑必须关闭。我想按原样读取每行(包括空格),直到换行符为止。任何帮助表示赞赏。
void initialize(string front[], string back[], ifstream &inFile)
{
string fileName = "DevDeck.txt"; //Filename
string line;
inFile.open(fileName); //Open filename
if (!inFile)
{
cout << "Couldn't open the file" << endl;
exit(1);
}
//Create the parallel arrays
while (!inFile.eof())
{
for (int index = 0; index < 4; index++)
{
getline(inFile, line);
front[index] = line; //Store in first array
getline(inFile, line);
back[index] = line; //Store in second array
}
}
}
最佳答案
您的循环for (int index = 0; index < 4; index++)
具有错误的条件,因为您总共需要4个字符串,但是在每个循环中您需要2个字符串,所以现在您将获得8个字符串。
我试图用这种更改来运行您的代码,如下所示:
int main()
{
string front[2];
string back[2];
ifstream inFile;
initialize(front, back, inFile);
cout << front[0] << endl << back[0] << endl << front[1] << endl << back[1];
return 0;
}
对我来说效果很好。它显示:
line1
line2
line3
line4
为了进一步帮助您,您应该提供
DevDeck.txt
文件和调用此函数的代码段。