Input and output of files with calculation

Im trying to read a file, calculate some value in the file, and output in a new file. I couldn't get it to show the first line(Miller Andrew). Need some guidance here. Am new to C++.

Input File
Miller Andrew 65789.87 5
Green Sheila 75892.56 6
Sethi Amit 74900.50 6.1

Output File
Green Sheila 80446.11
Sethi Amit 79469.43

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{

    string firstName;
    string lastName;
    string str;
    double currentSalary;
    double newSalary;
    double percentPayInc;

    //Declare stream variables
    ifstream inFile;
    ofstream outFile;

    //Open file
    inFile.open("Ch3 _ Ex6Data.txt");
    outFile.open("Ch3 _ Ex60utput.txt");

    outFile << fixed << showpoint;
    outFile << setprecision(2);

    while(getline(inFile,str))
    {
        inFile >> firstName >> lastName >> currentSalary >> percentPayInc;
        newSalary = currentSalary/100 * (100 + percentPayInc);
        outFile << firstName << setw(10) << lastName << setw(10) << newSalary << endl;

    }

    inFile.close();
    outFile.close();

    return 0;

}


Try this:
1
2
3
4
5
while(inFile >> firstName >> lastName >> currentSalary >> percentPayInc)
{
  newSalary = currentSalary/100 * (100 + percentPayInc);
  outFile << firstName << setw(10) << lastName << setw(10) << newSalary << endl;
}
Many thanks. But would also like to know why my getline would not work. I understand the solution you provided though.
But would also like to know why my getline would not work.

This line
 
    while(getline(inFile,str))
will read the file line by line into the string str.

The question then is where inside the body of the loop (lines 31 to 36) does the program make use of the contents of that string str? (clue: it doesn't).

One thing you might do is to use a stringstream to parse the contents of the string (requires header <sstream>)
1
2
3
4
5
6
7
8
9
    while (getline(inFile,str))
    {
        istringstream ss(str);
        if (ss >> firstName >> lastName >> currentSalary >> percentPayInc)
        {
            newSalary = currentSalary/100 * (100 + percentPayInc);
            outFile << firstName << setw(10) << lastName << setw(10) << newSalary << endl;
        }
    }
Topic archived. No new replies allowed.