使用getline从文本文件创建2个并行字符串数组

问题描述 投票:0回答:1

对于此任务,我打开一个文本文件并尝试将第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
        }
    }

}
c++ arrays loops file-io istream
1个回答
1
投票

你的循环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文件和调用此函数的代码段。

© www.soinside.com 2019 - 2024. All rights reserved.