c++ - 将两个文件读入向量第一个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;
}
解决方案
您的变量Payrate
是 的向量double
。
为了为其提供要存储的新值,您使用File >> a
.
但是变量a
有类型int
;如果此时的内容File2
是12.34
例如,那么12
将只提取以初始化a
。
该整数值被静默转换为double
并存储在Payrate
.
此时,剩余的以File2
开头.34
。
下一次迭代,再次尝试提取一个整数以将其放入EmpId2
.
但这失败了,因为整数不能以字符开头.
,因此第二个while
循环停止。
推荐阅读
- asp.net-core - 具有招摇属性的 CreatedAtRouteResult
- python - python ValueError:解包的值太多(预期....)
- javascript - 允许按钮被点击一次 JavaScript
- javascript - 用调试版本替换 V8 版本的 Chrome
- three.js - Three.js:可以在 BufferGeometry 中使用多种材质而无需多次绘制调用?
- matlab - 如何从单元格数组创建双打?
- angular - 动态最小/最大 FormGroup 验证
- javascript - 的意思 !!以及如何使用它
- angular - 在 Angular 中使用 Observer 作为 Observable
- ruby-on-rails - 如何指定与 factory_bot 的关联?