Printing/Saving a Payroll Chart This code was inspired by this question: Payroll Program.  I saw lots of ways I thought the code could be improved.  So much so that I thought it wouldn't be particularly constructive to post all of it as an answer to that question.  Essentially, I wanted to basically rewrite the whole thing from scratch.

So I did.  But I'm far from a C++ expert, so tell me how to make this even better:

#include &lt;cstdlib&gt;
#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iomanip&gt;
#include &lt;vector&gt;
#include &lt;sstream&gt;

const double WORK_WEEK_HOURS = 40;
const double OVERTIME_RATE = 1.5;

struct employee {
    int id;
    double payrate;
    double hours;
};

void payroll();
std::string fetchFileName();
employee fetchEmployee();
double wagesForEmployee(employee e);
bool askUser(std::string s);
std::string employeesToString(std::vector&lt;employee&gt; e);
void displayEmployees(std::vector&lt;employee&gt; e);
void saveEmployeesToFile(std::vector&lt;employee&gt; e);


int main(int argc, const char * argv[]) {
    payroll();
    return 0;
}

void payroll() {
    std::vector&lt;employee&gt; employees;

    do {
        employees.push_back(fetchEmployee());
    } while (askUser("Would you like to enter more employees? (y/n): "));

    if (askUser("Would you like to view the information you entered? (y/n): ")) {
        displayEmployees(employees);
    }

    if (askUser("Would you like to save the information you entered to file? (y/n): ")) {
        saveEmployeesToFile(employees);
    }
}

bool askUser(std::string s) {
    char answer;
    std::cout &lt;&lt; s;
    std::cin &gt;&gt; answer;
    return (answer == 'y' || answer == 'Y');
}

employee fetchEmployee() {
    employee e;
    e.id = -1;
    e.payrate = -1;
    e.hours = -1;

    do {
        std::cout &lt;&lt; "Enter the employee ID: ";
        std::cin &gt;&gt; e.id;
    } while(e.id &lt; 0);

    do {
        std::cout &lt;&lt; "Enter the payrate: ";
        std::cin &gt;&gt; e.payrate;
    } while (e.payrate &lt; 0);

    do {
        std::cout &lt;&lt; "Enter the hours worked: ";
        std::cin &gt;&gt; e.hours;
    } while (e.hours &lt; 0);

    return e;
}

double wagesForEmployee(employee e) {
    if (e.hours &lt; 0 || e.payrate &lt; 0) {
        return 0;
    }
    double wages = 0;
    if (e.hours &gt; WORK_WEEK_HOURS) {
        wages += (e.hours - WORK_WEEK_HOURS) * OVERTIME_RATE * e.payrate;
    }
    wages += std::min(e.hours, WORK_WEEK_HOURS) * e.payrate;
    return wages &gt; 0 ? wages : 0;
}

std::string employeesToString(std::vector&lt;employee&gt; e) {
    std::stringstream ss;

    ss &lt;&lt; std::setw(10) &lt;&lt; "ID" &lt;&lt; std::setw(10) &lt;&lt; "Rate" &lt;&lt; std::setw(10) &lt;&lt; "Hours" &lt;&lt; std::setw(10) &lt;&lt; "Wage" &lt;&lt; std::endl;
    ss &lt;&lt; "---------------------------------------------------------" &lt;&lt; std::endl;

    for (int i = 0; i &lt; e.size(); ++i) {
        employee curEmp = e.at(i);
        ss  &lt;&lt; std::setw(10) &lt;&lt; curEmp.id &lt;&lt; std::setprecision(2) &lt;&lt; std::fixed
            &lt;&lt; std::setw(10) &lt;&lt; curEmp.payrate &lt;&lt; std::setprecision(2) &lt;&lt; std::fixed
            &lt;&lt; std::setw(10) &lt;&lt; curEmp.hours &lt;&lt; std::setprecision(2) &lt;&lt; std::fixed
            &lt;&lt; std::setw(10) &lt;&lt;  wagesForEmployee(curEmp) &lt;&lt; std::endl;
    }

    return ss.str();
}

void displayEmployees(std::vector&lt;employee&gt; e) {
    std::cout &lt;&lt; employeesToString(e) &lt;&lt; std::endl;
}

void saveEmployeesToFile(std::vector&lt;employee&gt; e) {
    std::ofstream outputFile;
    std::string fileName;

    std::cout &lt;&lt; "Enter a file name: ";
    // TODO: Safety checking for illegal file name characters, etc.
    std::cin &gt;&gt; fileName;
    fileName += ".pay";
    outputFile.open(fileName.c_str());
    outputFile &lt;&lt; employeesToString(e);
    outputFile.close();

    std::cout &lt;&lt; "Successfully saved to " &lt;&lt; fileName;
}
double wagesForEmployee(employee e);
bool askUser(std::string s);
std::string employeesToString(std::vector&lt;employee&gt; e);
void displayEmployees(std::vector&lt;employee&gt; e);
void saveEmployeesToFile(std::vector&lt;employee&gt; e);


When you're only reading from a variable and not modifying it, you should take it by const reference. Taking it by value like this means that you copy it. 

This is particularly bad in displayEmployees since it makes a copy of the entire employee vector then passing that copy to employeesToString which then makes another copy.



e.id = -1;
e.payrate = -1;
e.hours = -1;

do {
    std::cout &lt;&lt; "Enter the employee ID: ";
    std::cin &gt;&gt; e.id;
} while(e.id &lt; 0);


Rather interestingly, you've manged to stumble across a backwards-compatibility breaking change in C++11. As per cppreference:

Before C++11:


  If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.


Since C++11:


  If extraction fails, zero is written to value and failbit is set.


This means that compiled under C++11 or newer, this code is wrong. A better approach is to simply check the result of the extraction directly:

do {
    std::cout &lt;&lt; "Enter the employee ID: ";
} while(!(std::cin &gt;&gt; e.id));


Note that this has the behavior of checking whitespace delimited words. In other words, if you want to skip the rest of the line on erroneous input, you'll need to do something likely involving std::getline to eat the rest of the line. As it is, entering something like a b c 5 would output the prompt text 4 times but only actually allow the user to provide input once. (And it would exit the loop with e.id == 5.)



int main(int argc, const char * argv[]) {
    payroll();
    return 0;
}



I'd probably just pull payroll up into main since main doesn't do anything else.
Omitting return 0 silently inserts return 0. In other words, when a program only exits with a success status, you can omit the return statement so that people reading the code can see that at a glance.
If you don't use argc and argv, I wouldn't bother to take them. int main() is just as valid.




double wagesForEmployee(employee e) {
    // #1
    if (e.hours &lt; 0 || e.payrate &lt; 0) {
        return 0;
    }
    double wages = 0;
    // #2
    if (e.hours &gt; WORK_WEEK_HOURS) {
        wages += (e.hours - WORK_WEEK_HOURS) * OVERTIME_RATE * e.payrate;
    }
    // #2
    wages += std::min(e.hours, WORK_WEEK_HOURS) * e.payrate;
    // #3
    return wages &gt; 0 ? wages : 0;
}



If you're going to start applying business rules to employee, I'd put them in the employee class. This would unfortunately complicate complicate the code to prompt for employee information on the command line though.
Super minor and completely opinion: I would calculate normal wages and then add overtime on top. It threw me for a second to realize that overtime was being done first.
When wages &gt;= 0, this is a (logical) no-op. That means that you're verifying that wages are positive. But, earlier in the function, you've verified that e.hours is nonnegative and payrate is nonnegative. OVERTIME_RATE is also presuambly nonnegative. In other words, why is this check here?


As a general note: don't hide error conditions. 0 is presumably a valid return from this function, so using it as an error sentinel is throwing away information. Instead, you need to either assert or throw an exception when you get unexpected inputs. Which you do depends on if you consider invalid inputs programmer error or user error. Personally, I would use assert here since I would expect the consuming programmer to provide a sane employee. (Actually I wouldn't check it at all, but some might say I err too far on the side of anti-precondition-verification.)

Another general note: this is a function that is oriented around an employee instance. It's also deeply aware of the internals of an employee object, and it's coupled to it. You see where I'm going with this, but just in case: this should be a method on the employee class. Stop seeing employee as a data bag, and start seeing it as a class. The e.hours &gt;= 0 and e.payrate &gt;= 0 conditions can be handled on the class, and this method would fit naturally onto it. You could even implement operator&lt;&lt;(ostream&amp;) on it to simply printing it (though personally I have mixed feelings on human aimed operator&lt;&lt;(ostream&amp;) implementations).



With regards to your employee outputting, you should have a function to output a single employee and then loop over that.

Also, Converting employees to a string and then outputting that string is incredibly inefficient. A better approach in C++ than building strings and outputting them is to output to streams and then build a string from that if you so desire. For example:

std::ostream&amp; outputEmployee(ostream&amp; os, const employee&amp; e) {

    // You would of course want to do proper formatting -- just a lazy example.
    // Note that a new line is not included. That is because the newline implies some form of looping is happening, but this function operates on a single employee.
    os &lt;&lt; e.id &lt;&lt; ' ' &lt;&lt; e.payrate &lt;&lt; ' ' &lt;&lt; e.hours;

    return os; // So the caller can easily check success ala if (outputEmployee(os, emp)) { ... }

    // In a real function, I would be tempted to put the return in the same line as the stream writing.
    // That has the same effect, but it saves a useless `return os;` line.
    // Example: return os &lt;&lt; e.id &lt;&lt; ... ;

}

std::string employeeToString(const employee&amp; e) {
    std::ostringstream oss;
    // If you wanted to be really paranoid, you could check oss after this call.
    // Nothing should (reasonably) fail though, so meh.
    outputEmployee(oss);
    return oss.str();
}


This is pretty much the exact same process you wrote, but the overhead of buffering into a string only to dump out to a stream is avoided.

As mentioned earlier, you could override operator&lt;&lt;(ostream&amp;). That would have the advantage of being a tiny bit cleaner to call (std::cout &lt;&lt; emp &lt;&lt; '\n'), and interestingly enough, it would also allow you to use some standard library tricks. For example, if you wanted to loop over outputting a collection of employees:

std::copy(std::begin(employees), std::end(employees),
          std::ostream_iterator&lt;employee&gt;(std::cout, "\n"));


Reading employees in can be done in a similar way if operator&gt;&gt; is overloaded:

std::vector&lt;employee&gt; employees;
std::copy(std::istream_iterator&lt;employee&gt;(std::cout), 
          std::istream_iterator&lt;employee&gt;(),
          employees);


As mentioned in passing earlier though, human aimed &gt;&gt; and &lt;&lt; make me a little uncomfortable (at least when the operators are defined directly on the class and not some kind of formatting decorator). I more of see them as debugging methods or methods for automatic reading (like parsing in a file or something instead of prompting a user). 



I don't like how much saveEmployeesToFile does. I would pull the prompting for file name and opening of the file into at least 1 function and have saveEmployeesToFile take an ostream&amp;. Happy side effect: you can then easily support outputting to std::cout if you want to pass that instead of a file stream.



With regards to saveEmployeesToFile:


Provided that functions stay small and focused, std::ofstream::close() is mostly noise. The file will be closed on destruction anyway.
If you prompt for the file name before you define the std::ofstream instance, you can avoid the open call.
You should verify that the file was successfully opened.




#includes should be alphabetized (though grouped by source first -- local includes first then 3rd party libraries and the standard library).