1

Below is the code that I am working with, it is supposed to read the information from the Salary Data which contains names and current salary and a percentage increase and then write the new information onto the NewData file. Well it reads the first line and rewrites in over and over endlessly onto the new file. It needs to be able to read each line and write each line in the salary file.

/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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;
}
Adam
  • 31
  • 1
  • 1
  • 3
  • `while (! fin.eof()) {` [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – drescherjm Oct 09 '19 at 02:13

1 Answers1

1

Instead of

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

try to put fin >> inside the while loop

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

Because fin >> can cause eofbit in one >> call and badbit in the next >> call.

fadedreamz
  • 1,013
  • 1
  • 8
  • 17