This is code for a project I have recently almost completed. The code takes a gross value and then does some math to get a bunch of new values. My final instruction is to output the console output into a file. I need both a console output and a file output. My issue is I have been trying for almost a day to figure out how to output into a file with printf. If anyone has a solution it would be much appreciated.
#include <iostream> #include <fstream> using namespace std; int main() { string FirstName; // declaring variables string LastName; double gross; double federalTax; double stateTax; // each variable will be holding the total taxed amount for each category double ssTax; // example if stateTax is 3.5%, then the stateTax variable will be 3.5% of gross double mmTax; double pensionPlan; double healthIns; double netDeduct; double netPay; cout << "Please enter your first name: "; // prompting for user input and storing in variables cin >> FirstName; cout << "\nPlease enter your last name: "; cin >> LastName; cout << "\nPlease enter your gross paycheck amount: "; cin >> gross; federalTax = gross * .15; // the math of the taxing stateTax = gross * .035; ssTax = gross * .0575; mmTax = gross * .0275; pensionPlan = gross * .05; healthIns = 75; netDeduct = federalTax + stateTax + ssTax + mmTax + pensionPlan + healthIns; netPay = gross - netDeduct; cout << endl,cout << FirstName + " " + LastName; cout << endl; // printing of the results printf("Gross Amount: %............ $%7.2f ", gross); cout << endl; printf("Federal Tax: %............. $%7.2f ", federalTax); cout << endl; printf("State Tax: %............... $%7.2f ", stateTax); cout << endl; printf("Social Security Tax: %..... $%7.2f ", ssTax); cout << endl; printf("Medicare/Medicaid Tax: %... $%7.2f ", mmTax); cout << endl; printf("Pension Plan: %............ $%7.2f ", pensionPlan); cout << endl; printf("Health Insurance: %........ $%7.2f ", healthIns); cout << endl; printf("Net Pay: %................. $%7.2f ", netPay); cout << endl; }
std::cout. See also<iomanip>, andsetw,ios::right,ios::left,ios::fill. Also, prefer to use'\n'tostd::endl. Thestd::endlhas additional overhead to a newline.fprintfwrites to a file in C.std::ofstreamis an output file stream in C++.fmt::print(fs, "Net Pay: %... ${:7.2f} ", netPay);printfandfprintf) or C++ streams (std::cout, std::ofstream`). Mixing them works, but is confusing.