How to save data to text file in C++

 In this post, I would like to share example how to save data to text file in C++.

Description:

This small program is allowed you to calculate salary for staff by input some information such Name, Gender, Tel , fee per hour , number of work hour and then save it to text file.

code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// function to save file text file: 
void SaveFile()
{
   string s_name , gender, address , tel;
   float hour;
   float hour_fee;
   ofstream Addfile;
   char choose;
   bool Again=true;
   float salary =0;

     //Open file      
     Addfile.open("Staffinfo.txt",fstream::in | fstream::out | fstream::app);
     /*Staffinfo.txt is already created before debug this program 
      for example if your project folder name's Staff, so the Staffinfo.txt's location_ is in Visual Studio 2010\Projects\Staff\Staff */
     while (Again)
     {
         //input data
         cout<<" staff's name : "; cin>>s_name;
         fflush(stdin);
         cout<<"\t gender : "; cin>>gender;
         cout<<"\t address  : "; cin>>address;
         cout<<"\t tel : "; cin>>tel;
         cout<<"\n\t Salary for staff : "<<endl;
         cout<<"\t fee per hour : "; cin>>hour_fee;
         cout<<"\t number of hour : "; cin>>hour;
         salary = (hour_fee * hour);
         cout<<"\t staff salary is :"<<endl<<endl;
             
         //Write data to text file
         Addfile<<"Staff information"<<endl;
         Addfile<<"\t Staff name : "<<s_name<<endl;
         Addfile<<"\t Gender : "<<gender<<endl;
         Addfile<<"\t Adrress : "<<address<<endl;
         Addfile<<"\t Tel : " <<tel<<endl;
         Addfile<<"Salary for staff"<<endl;
         Addfile<<"\t fee per hour : "<<hour_fee<<endl;
         Addfile<<"\t number of work hour :"<<hour<<endl;
         Addfile<<"\t Salary : "<<salary<<endl;
         Addfile<<"_________________________________________"<<endl;
         cout<<"Do you want to input more staff? (Y or N) : "; cin>>choose;
         if (choose=='Y'||choose=='y')
         {
             Again=true;
         }
         else if(choose=='N' || choose=='n')
         {
              Again=false;
         }
       }
}
                
int _tmain(int argc, _TCHAR* argv[])
{
   Start:
   SaveFile();
   cout<<" \n++ Do want to exit (Press Y to continue or N to exist):"; cin>>choose;
    if (choose=='Y'||choose=='y')
      {
         system("cls");
         go to Start;
         break;
       }
      else if(choose=='N' || choose=='n')
       {
          exit(0);
       }
            
       system("Pause");
       return 0;
}

Done .... Hope this post is helpful for you.
How to save data to text file in C++ How to save data to text file in C++ Reviewed by BeiLover on 11:56 AM Rating: 5

No comments:

Powered by Blogger.