gpt4 book ai didi

c++ - Code Endless 写入文本文件的第一行

转载 作者:行者123 更新时间:2023-11-30 04:43:25 24 4
gpt4 key购买 nike

下面是我正在使用的代码,它应该从薪资数据中读取包含姓名和当前薪资以及增长百分比的信息,然后将新信息写入 NewData 文件。好吧,它读取第一行并无休止地一遍又一遍地重写到新文件中。它需要能够读取和写入工资文件中的每一行。

/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
This Program does two things, first it reads data from a file, and second
it formats number output...

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


#include<iostream>
#include<fstream>
#include<string>
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
using namespace std;

int main()
{
// need an input file variable reference
ifstream fin;
ofstream myfile;

string lastName, firstName, str;
double salary, newSalary, percentIncrease;


// Output File

// Place the directory to the file you want to write to here.
myfile.open("C:/Users/Adam/Desktop/NewData.txt");

// What is being wrote to the output file.
myfile << "Writing this to a file.\n";


// Open the file named numbers.txt
fin.open("C:/Users/Adam/Desktop/SalaryData.txt"); // catch, file has
to be in the same folder as the .cpp

// OR

// use a EOF While loop to loop through an input file
// to be safe, always PRIME your EOF While loops



fin >> lastName >> firstName >> salary >> newSalary >> percentIncrease;
// reads first eligible item (in this case, an integer) from the file
while (! fin.eof()) {

newSalary = salary * (percentIncrease / 100) + salary;

cout << lastName << firstName << newSalary;
myfile << lastName << firstName << newSalary;
fin >> lastName >> firstName >> salary >> newSalary;

}

cout << endl;


cin.get();

return 0;
}

最佳答案

代替

fin >> lastName >> firstName >> salary >> newSalary >> percentIncrease;           
while (! fin.eof()) {
// do your stuff
fin >> lastName >> firstName >> salary >> newSalary;
}

尝试将 fin >> 放在 while 循环中

while( fin >> lastName >> firstName >> salary >> newSalary >> percentIncrease ) {
// do your stuff
}

因为 fin >> 会在一个 >> 调用中导致 eofbit,在下一个 >> 调用中导致 badbit。

关于c++ - Code Endless 写入文本文件的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58296056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com