Home > database >  What is the best way to use printf in output?
What is the best way to use printf in output?

Time:06-25

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;

}

CodePudding user response:

Side note: If you are coding in C then you should use the newer functionalities such as cout or fstream instead of printf of fprintf

Now, coming to your question: What you are probably looking for is fprintf()
Here's a snippet using the function that I just mentioned above:

   FILE * fp = fopen ("file.txt", "w ");
   fprintf(fp, "%s %f", "Your net pay is: ", netPay);

As you can see, it's quite similar to printf and that's why I think it should be self explanatory to you. The only big difference is passing a FILE pointer to it
Check these links out to learn more about fprintf() and fopen()

  •  Tags:  
  • c
  • Related