【问题标题】:Create 2 parallel string arrays from text file using getline使用 getline 从文本文件创建 2 个并行字符串数组
【发布时间】:2019-03-08 05:35:45
【问题描述】:

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

    您的循环 for (int index = 0; index &lt; 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 文件和调用此函数的代码。

    【讨论】:

    • 谢谢。看起来数组大小已关闭。 //Global constant const int NUMCARDS = 2; /inside main string front[NUMCARDS]; string back[NUMCARDS]; ifstream infile; 现在很好用。泰。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2012-05-26
    相关资源
    最近更新 更多