I have created a banking program in C++
and every time a user creates account their details are to be stored into a text file. I have created the code that does this, but when I create the first account it will store the information, and when I create the second it overwrites it, which is not what I want to to do yet.
Here is the code I am using:
ofstream myfile;
myfile.open("test.txt"); //open myfile.txt
myfile << setw(10) << "=Account Number=" << setw(20) << "=Customer Name=" << setw(20) << "=Balance=" << endl;
myfile << "=========================================================================================";
myfile << setw(10) << Account_no << setw(20) << name << setw(20) << address << setw(20) << intialAmount; //send values
myfile.close();//close file
How can I get it to move to a new line after the first customer has been created?
Constructor of ofstream takes a mode option ( see here ). So open it like :
ofstream myfile("test.txt",std::ofstream::app);
To build upon Kiroxas's code, this one first checks if there's already a customer:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ifstream fil("test.txt");
string f((istreambuf_iterator<char>(fil)), istreambuf_iterator<char>());
//read into string
fil.close();
if (f.length() < 1) // if no previous customer in file
{
ofstream myfile;
myfile.open("test.txt");
myfile << setw(10) << "=Account Number=" << setw(20) << "=Customer Name="
<< setw(20) << "=Balance=" << endl;
myfile << "============================================"
<< "=============================================";
myfile << setw(10) << Account_no << setw(20)
<< name << setw(20) << address
<< setw(20) << intialAmount; //send values to start of file
myfile.close(); //close file
}
else //if file contains previous customer
{
ofstream myfile;
myfile.open("test.txt", ios::app);
//ios::app tells it to write to the end of the file
myfile << setw(10) << "=Account Number=" << setw(20)
<< "=Customer Name="
<< setw(20) << "=Balance="
<< endl;
myfile << setw(10) << Account_no << setw(20)
<< name << setw(20) << address
<< setw(20) << intialAmount; //send values
}
}
NOTE:
ios::app
has the same function as std::ofstream::app
, it's just shorter!
Do not expect it to compile because I have not declared your account info variables ( Account_no
and et cetera). Until you declare them, it won't compile...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.