issues with setprecision or fixed.. not sure

Write your question here.

The inData file looks like this.

1
2
3
Miller Andrew 65789.87 5
Green Sheila 75892.56 6
Sethi Amit 74900.50 6.1


Currently the outData file looks like this

1
2
3
 Andrew Miller 69079.4
 Sheila Green 80446.1
 Amit Sethi 79469.4


I would like the outData file to look like this

1
2
3
 Andrew Miller 69079.40
 Sheila Green 80446.10
 Amit Sethi 79469.40


full code is here.

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
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

int main(int argc, const char * argv[])
{
    ofstream outFile;
    outFile.open("outData.txt", ifstream::out);
    if (!outFile) {
        cerr << "Error: file could not be opened" << endl;
        return -2;
    }


    ifstream inFile;
    inFile.open("inData.txt", ifstream::in);
    if (!inFile) {
        cerr << "Error: file could not be opened" << endl;
        return -1;
    }


    double salary, rate, newsal;
    string fname, lname;

    while (inFile >> lname >> fname >> salary >> rate) {
        newsal = ((rate*.01) *salary) +salary;
        outFile <<" "<< fname<<" "<< lname <<" "<<newsal << endl;
    }
    
    inFile.close();
    outFile.close();

    return 0;
}




I pretty sure it is an issue with
setprecision as I am not that strong in it.
but very possible I am wrong about this as well.
Thanks in advance for any help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>

int main()
{
    const double d = 69079.4017607 ;

    std::cout << d << '\n' ; // 69079.4

    std::cout << std::fixed // in fixed point notation
               << std::setprecision(2) // with two digits after the decimal point
               << d << '\n' ; // 69079.40

    std::cout << std::setprecision(3) // with three digits after the decimal point
               << d << '\n' ; // 69079.402

    std::cout << std::setprecision(4) // with four digits after the decimal point
               << d << '\n' ; // 69079.4018
}
closed account (28poGNh0)
You may want to alter your line 31 with this one
outFile <<" "<< fname<<" "<< lname <<" "<< fixed << setprecision(2) << newsal << endl;
I think my IDE was acting up. I allowed me to copy and paste the function call in, (fixed) but if I typed it it would throw an error.

Thank you for your help!
This seemed to solve it.

1
2
3
4
5
    while (inFile >> lname >> fname >> salary >> rate) {
        outFile << fixed << setprecision(2);
        newsal = ((rate*.01) *salary) +salary;
        outFile <<" "<< fname<<" "<< lname <<" "<<newsal << endl;
    }


Edit...
Going to go with your advise Techno...
seems to make more procedural sense to me, than what I was doing!

Thanks again everyone!
Last edited on
Topic archived. No new replies allowed.