Why won't this piece of my code write to file - c++

I am developing a C++ banking system.
I am able to get the float, newbal, values correctly and when I try to write to file, there is no data in the file.
else if (x == 2)
{
cout << "You have selected option number 2. Deposit.\n";
cout << "Please enter you account ID: ";
cin >> ID;
file.open("C:\\Users\\Raggulddon\\Desktop\\C++ supplement\\Cust_" + ID + ".dat", ios:: in | ios::out | ios::binary);
if (!file)
{
cout << "Sorry the requested account could not be located.\n";
}
else
{
file >> firstname >> lastname;
cout << endl << firstname << " " << lastname << endl;
cout << "-----------------------------------\n";
string line;
while (getline(file, line))
{
// stringstream the getline for line string in file
istringstream iss(line);
if (iss >> date >> amount)
{
cout << date << "\t\t$" << showpoint << fixed << setprecision(2) << amount << endl;
famount += amount;
}
}
cout << "Your balance is $" << famount << endl;
cout << "How much would you like to deposit today: $";
cin >> amountinput;
float newbal = 0;
newbal = (famount += amountinput);
cout << "\nYour new balance is: $" << newbal << ".\n";
file << date << "\t\t" << newbal; //***This should be writing to file
but it doesn 't.
file.close();
The text file looks like this:
Tony Gaddis
05/24/12 100
05/30/12 300
07/01/12 -300
// Console Output looks like this
Tony Gaddis
05/24/12 100
05/30/12 300
07/01/12 -300
Your balance is: #1
How much wuld you like to deposit: #2
Your new balance is: #1 + #2
write to file
close file.
// exits to main loop::::
How can I make it write to file and save it, and why is this happening.
I tried doing it with ostringstream as well considering how I used istringstream for the input. But it didn't work either:
float newbal=0;
newbal = (famount += amountinput);
ostringstream oss(newbal);
oss << date << "\t\t" << newbal;
I am trying to self teach C++ so any relevant information would be kindly appreciated.

If you want to write a text file, you should not use "ios::binary", when opening the file.

Related

cin doesnt take another input correctly after a set of input from while

This is the file_processing_tutor.cpp file:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include "ClientData.h"
using namespace std;
void outputline(int, const string &, double);
void outputlineDAT(ostream&, const ClientData &);
int main() {
cout << endl << "Phase 1 Writing Data to txt" << endl;
cout << "Make Sure Input is already ready before running" << endl;
ofstream outClientFile("C:/Users/User/Desktop/Streaming DT Data/test.txt", ios::out);
if(!outClientFile){
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
}
cout << "Enter the account, name, and balance" << endl << "Enter end-of-file to end input." << endl;
int count_input = 0;
int account;
string name;
double balance;
while(cin >> account >> name >> balance){
++count_input;
outClientFile << account << ' ' << name << ' ' << balance << endl;
cout << "? (Input Count = " << count_input << ") " << endl;
}
cout << endl << endl << "Phase 2 Reading Data from txt" << endl;
ifstream inClientFile("C:/Users/User/Desktop/Streaming DT Data/test.txt", ios::in);
if(!inClientFile){
cerr << "File Could not be Opened" << endl;
exit(EXIT_FAILURE);
}
cout << left << setw(10) << "Account" << setw(13) << "Name" << "Balance" << endl << fixed << showpoint;
while(inClientFile >> account >> name >> balance){
outputline(account, name, balance);
}
cout << endl << "Phase 3 Writing 100 Blank Records to Random Access File .Dat" << endl;
fstream outCredit("C:/Users/User/Desktop/Streaming DT Data/credit.dat", ios::out | ios::in | ios::binary);
if(!outCredit){
cerr << "File Could not be opened" << endl;
exit(EXIT_FAILURE);
}
ClientData blankClient;
for(int i = 0; i < 100; ++i){
outCredit.write(reinterpret_cast <const char *>(&blankClient), sizeof(ClientData));
}
cout << endl << "Phase 4 Writing Data Randomly to a Random Access File .Dat" << endl;
string firstName;
string lastName;
cout << "Enter Account Number (1 to 100, 0 to end input)\n?";
ClientData client;
cin >> account;
cout << "Account Input: " << account << endl;
while(account > 0 && account <= 100){
cout << "Enter lastname, firstname, balance \n?";
cin >> lastName >> firstName >> balance;
client.setAccountNumber(account);
client.setLastName(lastName);
client.setFirstName(firstName);
client.setBalance(balance);
outCredit.seekp((client.getAccountNumber() - 1) * sizeof(ClientData));
cout << "Enter Account Number (1 to 100, 0 to end input)\n?";
cin >> account;
}
return 0;
}
void outputline(int account, const string &name, double balance){
cout << left << setw(10) << account << setw(13) << name << setw(7)
<< setprecision(2) << right << balance << endl;
}
void outputlineDAT(ostream &output, const ClientData &record){
output << left << setw(10) << record.getAccountNumber() << setw(16)
<< record.getLastName() << setw(11) << record.getFirstName() << setw(10)
<< setprecision(2) << right << fixed << showpoint << record.getBalance() << endl;
}
Because I am using Sublime Text 3, I set my input in a file called inputf.in, this is all my raw input:
100 Jones 24.98
200 Doe 345.67
300 White 0
400 Stone -42.16
500 Rich 224.62
450 Harmond 412.5
3
Barker Doug 0
29
Brown Nancy -24.54
96
Stone Sam 34.98
88
Smith Dave 258.34
33
Dunn Stacey 314.33
0
And I see my output as follows from outputf.out:
Phase 1 Writing Data to txt
Make Sure Input is already ready before running
Enter the account, name, and balance
Enter end-of-file to end input.
? (Input Count = 1)
? (Input Count = 2)
? (Input Count = 3)
? (Input Count = 4)
? (Input Count = 5)
? (Input Count = 6)
Phase 2 Reading Data from txt
Account Name Balance
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62
450 Harmond 412.50
Phase 3 Writing 100 Blank Records to Random Access File .Dat
Phase 4 Writing Data Randomly to a Random Access File .Dat
Enter Account Number (1 to 100, 0 to end input)
?Account Input: 450
Problem:
So every output in above was ok, until it reached phase 4 where I get to input new data for account variable, Instead of get the input 3 (which is set from the input) it reoutputs the last account data (450) ignoring the cin input. thus it didn't input anything to a file called credit.dat.
Appreciate any pointers to the issues, Thankyou!

Adding to a file without erasing what is inside

I am writing a code that takes some input from the user and stores it in a file. My code is supposed to keep the old data and add the new data, but every time I run the code the old data that was in the file gets replaced by the new one.
if(input == 1){
outFile.open("personnel2.dat");
int numRecords = 0;
do{
cout << "#1 of 7 - Enter Employee Worker ID Code(i.e AF123): ";
cin >> id;
cout << "#2 of 7 - Enter Employee LAST Name: ";
cin >> lastN;
cout << "#3 of 7 - Enter Employee FIRST Name: ";
cin >> firstN;
cout << "#4 of 7 - Enter Employee Work Hours: ";
cin >> workH;
cout << "#5 of 7 - Enter Employee Pay Rate: ";
cin >> payRate;
cout << "#6 of 7 - Enter FEDERAL Tax Rate: ";
cin >> federalTax;
cout << "#7 of 7 - Enter STATE Tax Rate: ";
cin >> stateTax;
outFile << id << " " << lastN << " " << firstN << " " << workH << " " << payRate << " "
<< federalTax << " " << stateTax << "\n";
numRecords++;
cout << "Enter ANOTHER Personnel records? (Y/N): ";
cin >> moreRecords;
}while(moreRecords != 'N' && moreRecords != 'n');
outFile.close();
cout << numRecords << " records written to the data file.\n";
}
Change outFile.open("personnel2.dat");
to
outFile.open("personnel2.dat", std::fstream::app);
to set the mode to append, assuming you are using fstream::open().
Assuming that outfile is instance of std::ofstream, The reason behind that is that when you use open() function on ofstream object, the file is opened in ios_base::out mode which enforces removal of previous content before inserting new one.
In order to append the data, you have to explicitly specify the append mode.
Example:
#include <fstream> // std::ofstream
int main () {
std::ofstream ofs;
ofs.open ("test.txt", std::ofstream::out | std::ofstream::app);
ofs << " more lorem ipsum";
ofs.close();
return 0;
}
Source: http://www.cplusplus.com/reference/fstream/ofstream/open/
In your case, you have to change it in this way:
outFile.open("personnel2.dat", std::ofstream::out | std::ofstream::app);

Why is the first line shifted one space to the right?

Okay so me and a few colleagues were working on an assignment for class. I completed it to my fullest extent; however, there is one thing that neither I nor any of my colleagues could fix. I searched for hours online but couldn't fine the answer I needed.
The first line that is printed after the data is read from the file is always shifted 1 space to the right. That is my only problem. The string is not shifted, but everything is. We checked for spaces, tabs, and extra symbols, we tried switching up the file we were reading from all to achieve nothing. I would really appreciate it if someone could point out what is wrong with my program. Thanks in advance!
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ifstream inputFile;
cout << "Please enter the file you would like to open: ";
string filename;
cin >> filename;
inputFile.open(filename);
if(inputFile.fail())
{
cout << "Error: File failed to open or was not found..." << endl;
}
else
{
cout << "File opened" << endl;
string land;
double price, min, max, total, average, count;
count = 0;
min = 0;
max = 0;
total = 0;
while(inputFile.good())
{
getline(inputFile, land, '\t');
inputFile >> price;
cout << fixed << setprecision(2) << setw(40) << left << land << right << "$ " << price;
if(count == 0)
{
max = price;
min = price;
}
if(price > max)
{
max = price;
}
if(price < min)
{
min = price;
}
total += price;
count++;
}
inputFile.close();
average = total / count;
cout << endl << endl;
cout << setw(43) << "Average Price = $ " << average << endl;
cout << setw(43) << "Highest Price = $ " << max << endl;
cout << setw(43) << " Lowest Price = $ " << min << endl;
}
return 0;
}
What doesn't make sense to me is that it is a loop, so why is only the first one being shifted?
This is what was on the file I was using
Landmark 1258
Creekside 1840
Parkside 1575
Gallatyn Walk 1710
Oak Mill 1185
Cutler's Ridge 1495
Prairie Creek Cottages 1987
Waterview Mills 1505
Canterbury Courts 1300
Breckinridge Point 1205
The Junction 1699
The words and numbers should all be separated with a tab.
The Image shows the output I was always given.
The difference is that from the first line, variable "land" is "Landmark" while all the others have the \n in front of the name, taken from the previous line, ie "\nCreekside", "\nParkside" etc.
You could just delete the \n from the string name and then add it at the end of your std::cout:
while (inputFile.good())
{
getline(inputFile, land, '\t');
if (land[0] == '\n')
{
land.erase(0, 1);
}
inputFile >> price;
cout << fixed << setprecision(2) << setw(40) << left << land << right << "$ " << price << endl;
Now the outcome is formatted correctly!
It's an illusion. The first line is spaced correctly. Every other value you read in with getline will include a \n character, which is where inputFile >> price left off.
A quick fix is to ignore all characters to the end of line after reading price (requires you to include <limits>):
getline(inputFile, land, '\t');
inputFile >> price;
inputFile.ignore( numeric_limits<streamsize>::max(), '\n' );
cout << setw(40) << left << land << right << "$ " << price << endl;
A better approach is to always read lines in the first place. This is also a more correct loop condition, and a practise you should get into (this version uses <sstream>):
string line;
while( getline( inputFile, line ) )
{
istringstream line_ss( line );
if( getline( line_ss, land, '\t' ) >> price )
{
cout << setw(40) << left << land << right << "$ " << price << endl;
}
}

Issue with saving an edited infile to an outfile in c++

Im having an issue with the last section of coding on here. The // Copy files from infile to outfile. The program transfers my infile which is simply a an 8 digit number , 20392207,splits it up into individual digits using the .at method; and is supposed to save that output to an outfile. I cant figure out how to save the output to the outfile. Any advice?
infile looks as follows
20392207
program output looks like this
The input number :20392207
The number 1:2
The number 2:0
The number 3:3
The number 4:9
The number 5:2
The number 6:2
The number 7:0
The number 8:7
outfile is supposed to look like the program out put, but instead just looks like an exact copy of the infile.
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
string ifilename, ofilename, line, line2;
ifstream inFile, checkOutFile;
ofstream outFile;
char response;
int i;
// Input file
cout << "Please enter the name of the file you wish to open : ";
cin >> ifilename;
inFile.open(ifilename.c_str());
if (inFile.fail())
{
cout << "The file " << ifilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Output file
cout << "Please enter the name of the file you wish to write : ";
cin >> ofilename;
checkOutFile.open(ofilename.c_str());
if (!checkOutFile.fail())
{
cout << "A file " << ofilename << " exists.\nDo you want to continue and overwrite it? (y/n) : ";
cin >> response;
if (tolower(response) == 'n')
{
cout << "The existing file will not be overwritten. " << endl;
exit(1);
}
}
outFile.open(ofilename.c_str());
if (outFile.fail())
{
cout << "The file " << ofilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Copy file contents from inFile to outFile
while (getline(inFile, line))
{
cout << "The input number :" << line << endl;
for (i = 0; i < 8; i++)
{
cout << "The number " << i + 1 << ":";
cout << line.at(i);
cout << endl;
}
outFile << line << endl;
}
// Close files
inFile.close();
outFile.close();
} // main
Here we can see that outFile is only written to outside of the while loop:
while (getline(inFile, line))
{
cout << "The input number :" << line << endl;
for (i = 0; i < 8; i++)
{
cout << "The number " << i + 1 << ":";
cout << line.at(i);
cout << endl;
}
}
outFile << line << endl;
It has no chance of containing the same output as the console
Solution: Write inside the loop the same stuff that was written to the console:
while (getline(inFile, line))
{
cout << "The input number :" << line << endl;
outFile << "The input number :" << line << endl;
blah blah blah
}
But this looks like crap and a function makes like a better solution by eliminating duplication and upping re-usability.
void output(std::ostream & out,
const std::string & line)
{
out << "The input number :" << line << endl;
for (int i = 0; i < 8; i++)
{
out << "The number " << i + 1 << ":";
out << line.at(i);
out << endl;
}
}
and called:
while (getline(inFile, line))
{
output(cout, line);
output(outFile, line);
}
You need to write to outFile inside the while(getline(inFile, line)) loop.
[edit] see user4581301's answer for a more thorough treatment.

Learning c++ -- reading numbers from a file

Quick synopsis: I can write the data into the file correctly (I've checked the .txt file and it presents exactly as it should) but all I can read back is the last number inputted. So, if the last quiz grade I input is 85, that's all it will read back. (the studentNumber reads back fine.)
Thanks all! Still learning here ...
while (answer == 1)
{
cout << "What is the student ID?\n";
cin >> studentNumber;
cout << "\n";
cout << "How many quizzes did you take?\n";
cin >> numQuiz;
outputFile << "\n";
outputFile << studentNumber << "\n";
outputFile << "Number of quizzes: " << numQuiz << "\t" "Grades: ";
for (int quiz = 1; quiz <= numQuiz; quiz++)
{
cout << "Please enter the score for quiz " << quiz << "\t";
cin >> score;
total += score;
// cout << "The score is " << score << " .\n";
outputFile << score << "\t"; }
// outputFile << total;
cout << "Do you have a student's grades to input?\nIf yes, type 1. If no, type 0.\n";
cin >> answer;
cin.ignore();
}
outputFile.close();
fstream inputFile;
inputFile.open("grades2.txt");
inputFile >> studentNumber;
cout << studentNumber << "\n";
inputFile >> score;
cout << score << "\n";
You are using the wrong operator to read the data back. Instead of
inputFile << studentNumber;
you need to use
inputFile >> studentNumber;