首页 > 解决方案 > 将两个文件读入向量第一个while循环有效,但第二个只迭代一次?

问题描述

在我开始从另一个文件读取之前,我应该使用一个函数吗?我使用了 File1.close 但这没有帮助,我从 (File2 >> a) 读取的第二个 while 循环只迭代一次。我不知道如何解决这个问题。控制台输出只有我文件中的第一个值,然后停止。我正在读入向量的文件位于存储我的项目的正确位置。我做错了什么?

int main()
{
    int a;
    vector<int> EmpId1, EmpId2, hours;
    vector<double> Payrate, Paycheck;
    ifstream File1, File2;
    ofstream PayRoll("PayRoll.txt");

    // Open the file
    File1.open("HoursWorked.txt");
    if (!File1)
    {
        cout << "The file was not found." << endl;
        return 1;
    }

    // Read and print every word already in the file   
    while (File1 >> a)
    {
        EmpId1.push_back(a);
        File1 >> a;
        hours.push_back(a); 
    }

    for (unsigned int count = 0; count < EmpId1.size(); count++)
    {
        cout << EmpId1[count] << "***1****" << hours[count] << endl;
    }

    // Clear end of file flag to allow additional file operations
    File1.clear();
    File1.close();
        //Close if file cannot be found
    File2.open("HourlyRate.txt");
    if (!File2)
    {
        cout << "The file was not found." << endl;
        return 1;`enter code here`
    }

    // Read and print every word already in the file 
    while (File2 >> a)
    {
        EmpId2.push_back(a);
        File2 >> a;
        Payrate.push_back(a);
    }

    for (unsigned int count = 0; count < EmpId2.size(); count++)
    {
        cout << EmpId2[count] << "****2***" << Payrate[count] << endl;
    }

标签: c++

解决方案


您的变量Payrate是 的向量double
为了为其提供要存储的新值,您使用File >> a.
但是变量a有类型int;如果此时的内容File212.34例如,那么12将只提取以初始化a
该整数值被静默转换为double并存储在Payrate.

此时,剩余的以File2开头.34
下一次迭代,再次尝试提取一个整数以将其放入EmpId2.
但这失败了,因为整数不能以字符开头.,因此第二个while循环停止。


推荐阅读