Adding to a file without erasing what is inside - c++

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);

Related

Reading from text file until EOF infinite loop

I am working at my programming project for school and i came up with idea of "Student Manager Program".
The: name, roll, year, group, course, adress, email, contact, grade are stored as variables in class named Student.
Student's data is written by user keyboard input and saved in studentRecord.txt file, by object.
How can i prevent this while loop to be a not infinite loop. I can't find solution to this problem.
'''
//Displaying Students Record Table
void Student::display() {
system("cls");
ifstream file;
int total = 1;
int x;
cout << "\n-----------------------------Students Record Table-----------------------------" << endl;
file.open("studentRecord.txt");
if (!file) {
cout << "\n\t\t\tNo Data Is Present.";
file.close();
}
else {
file >> name >> roll >> year >> group >> course >> adress >> email >> contact >> grade;
while(!file.eof()) {
cout << "\n\n\t\t\t Student Consecutive Number: " << total++ << endl;
cout << "\t\t\t Student's Name: " << name << endl;
cout << "\t\t\t Student's ID Number: " << roll << endl;
cout << "\t\t\t Student's Year: " << year << endl;
cout << "\t\t\t Student's Group: " << group << endl;
cout << "\t\t\t Student's Course: " << course << endl;
cout << "\t\t\t Student's Adress: " << adress << endl;
cout << "\t\t\t Student's Email: " << email << endl;
cout << "\t\t\t Student's Contact: " << contact << endl;
cout << "\t\t\t Student's Final Grade: " << grade << endl;
file >> name >> roll >> year >> group >> course >> adress >> email >> contact >> grade;
}
if (total == 0) {
cout << "\n\t\t\tNo Data Is Present.";
}
}
do {
cout << "\n\t\t\t If You Want to Back at previous page press 0 and Enter: ";
cin >> x;
if (x == 0) {
file.close();
}
} while (x != 0);
}
'''

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;

Code not allowing user input in strings after first string

I have looked around and can't seem to find an answer to this. I am new to C++ and am attempting to write a program for a class that asks the user for the first and last names of 4 students and their ages. The program will then display the input names and ages and also display the average of the ages.
The issue I am having is that the program allows for input of the first name and age but then skips over the remaining three name input fields and only allows for the remaining three ages to be input.
I apologize if this ends up being a dumb question but I really am at a loss. Any help will be greatly appreciated.
Here is the code I have thus far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string studentname1;
cout << "Please enter the first student's full name:" << endl;
getline(cin, studentname1);
int age1;
cout << "Please enter the first student's age:" << endl;
cin >> age1;
string studentname2;
cout << "Please enter the second student's full name:" << endl;
getline(cin, studentname2);
int age2;
cout << "Please enter the second student's age:" << endl;
cin >> age2;
string studentname3;
cout << "Please enter the third student's full name:" << endl;
getline(cin, studentname2);
int age3;
cout << "Please enter the third student's age:" << endl;
cin >> age3;
string studentname4;
cout << "Please enter the fourth student's full name:" << endl;
getline(cin, studentname2);
int age4;
cout << "Please enter the fourth student's age:" << endl;
cin >> age4;
cout << "Hello from our group." << endl;
cout << "NAME AGE" << endl;
cout << studentname1 << " " << age1 << endl;
cout << studentname2 << " " << age2 << endl;
cout << studentname3 << " " << age3 << endl;
cout << studentname4 << " " << age4 << endl;
cout << "The average of all our ages is: " << (age1 + age2 + age3 + age4) / 4.00 << endl;
return 0;
}
Since the age variables are int, the cin >> age1; will leave the newline character in the input stream. When next you call getline(), you will get the remainder of that line - which is empty, and so on.
Also, you have a copy-paste bug in your code. getline(cint, studentname2); is run for students 2, 3 and 4.
You can either solve the problem by using getline() for all input:
string agestring;
getline(cin, agestring)
stringstream(agestring) >> age1;
or clear cin when you're done reading the age:
cin >> age1;
cin.ignore();

Binary File - Editing

Please help i am having trouble with this function. The code compiles and everything however it doesnt change anything in the file. I am so confused what i am supposed to do.... I am supposed to choose a record from the file to edit and then change it, my current code allows me to choose but when i edit the record nothing is stored?
void editRecord(Cookie &type)
{
fstream dataFile;
int num;
int count = 0;
dataFile.open("/Users/jordanmcpeek/Documents/2014_Summer/CSC_250/Unit_7/cookie.dat", ios::in | ios::out | ios::binary);
dataFile.read(reinterpret_cast<char *>(&type), sizeof(type));
// While not at the end of the file, display the records
while (!dataFile.eof())
{
// Display the records.
cout << endl;
cout << count << ". Description: ";
cout << type.description << endl;
cout << "Quantity Sold: ";
cout << type.quantity << endl;
cout << "Price: $";
cout << type.price << endl;
dataFile.read(reinterpret_cast<char *>(&type), sizeof(type));
count++;
}
cout << "Which record would you like to edit?: ";
cin >> num;
cout << endl;
cin.ignore();
dataFile.seekp(num * sizeof(type), ios::beg);
cout << "Please enter the new description for the cookie: ";
cin.getline(type.description, SIZE);
cout << endl;
do
{
cout << endl;
cout << "Please enter the new amount sold: ";
cin >> type.quantity;
cin.ignore();
}while(type.quantity < 0);
cout << endl;
do
{
cout << "Please enter the new price: $";
cin >> type.price;
cin.ignore();
}while(type.price < 0);
cout << endl;
// Change the record
dataFile.write(reinterpret_cast<char *>(&type), sizeof(type));
dataFile.close();
}

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

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.