Edit specific string in text file in C++ - c++

How to edit specific string in text file?
I use my logic but it's not working..
Really appreciate anyone help me
Here is my Add Function
void Admin::add_dvd()
{
string id, copy, title, genre, dir, rentdate, returndate, fee;
ofstream myfile("dvd_list.txt", ios::out | ios::app);
cin.get();
cout << "DVD ID: " << endl;
getline(cin, id);
cout << "Copy Number: " << endl;
getline(cin, copy);
cout << "Title: " << endl;
getline(cin, title);
cout << "Genre: " << endl;
getline(cin, genre);
cout << "Director: " << endl;
getline(cin, dir);
cout << "Rental Date: " << endl;
getline(cin, rentdate);
cout << "Return Date: " << endl;
getline(cin, returndate);
cout << "Rental Fee: " << endl;
getline(cin, fee);
myfile << endl << id << " | " << copy << " | " << title << " | " << genre << " | " << dir << " | " << rentdate << " | " << returndate << " | " << fee << endl;
myfile.close();
cout << "DVD Added." << endl;
system("pause");
}
This is the EDIT FUNCTION
void Admin::edit_dvd()
{
string id;
cout << "Enter DVD ID: " << endl;
cin >> id;
ifstream myfile("dvd_list.txt");
if (myfile.is_open())
{
while (!myfile.eof())
{
myfile >> dvd_id >> title >> genre >> dir >> rent_date >> return_date >> copy_num >> rent_fee;
if (id == dvd_id)
{
int choice;
cout << dvd_id << title << genre << dir << rent_date << return_date << copy_num << rent_fee << endl;
cout << "Which part you want to edit? " << endl;
cout << "1) DVD ID" << endl;
cout << "2) DVD Title" << endl;
cout << "3) Genre" << endl;
cout << "4) Director" << endl;
cout << "5) Rent Date" << endl;
cout << "6) Return Date" << endl;
cout << "7) Copy Number" << endl;
cout << "8) Rent Fee" << endl;
cout << "9) Cancel" << endl;
cout << "Enter number: " << endl;
cin >> choice;
switch (choice)
{
case 1:
{
string id;
cout << "Enter new DVD ID: " << endl;
cin >> id;
id = dvd_id;
}
case 2:
{
string ttl;
cout << "Enter new DVD Title: " << endl;
cin >> ttl;
ttl = title;
}
case 3:
{
string gen;
cout << "Enter new Genre: " << endl;
cin >> gen;
gen = genre;
}
case 4:
{
string director;
cout << "Enter new Director: " << endl;
cin >> director;
director = dir;
}
case 5:
{
string rdate;
cout << "Enter new Rent Date: " << endl;
cin >> rdate;
rdate = rent_date;
}
case 6:
{
string retdate;
cout << "Enter new Return Date: " << endl;
cin >> retdate;
retdate = return_date;
}
case 7:
{
string cnumber;
cout << "Enter new Copy Number: " << endl;
cin >> cnumber;
cnumber = copy_num;
}
case 8:
{
string rfee;
cout << "Enter new Rent Fee: " << endl;
cin >> rfee;
rfee = rent_fee;
}
case 9:
{ break; }
}
}
else
{
cout << "No data matched!" << endl;
break;
}
}
myfile.close();
}
}
And this is the Txt File Created from Add Function
DF17361 | 12 | Drake | Comedy | Frank | 12/2/2014 | 23/2/2014 | 10

Related

Problems reading edited data after modifying data file using fstream in C++

I'm currently making a record system for ticket booking as an assignment and facing problems when I want the data to read after modifying my file. I saw there were 2 options for me: eof or read in fstream.
The code for my modify records:
ifstream inFile;
ofstream outFile;
inFile.open("movieRecord.dat");
outFile.open("temp.dat");
inFile >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;
cout << "\tPlease Enter the Movie to Edit:";
cin.ignore();
cin.getline(editMovie,20);
titleMatch = strcmp (editMovie,item.movieName);
while (!inFile.eof()){
if (editMovie == item.movieName){
break;
}
else{
outFile << item.movieName << " " << item.movieTime << " " << item.hallNum << " " << item.moviePrice << endl;
break;
}
}
cout << "\tEditing " << editMovie << "..." << endl;
cin.clear();
cout << "\tReInsert Movie Title: ";
cin.getline(movieTitle,20);
cin.clear();
cout << flush;
cout << "\tEnter Time(ie:15.00): ";
cin >> movieTime2;
cout << flush;
cout << "\tEnter Hall Number for Movie: Hall ";
cin >> hallNumber;
cout << flush;
cout << "\tEnter Price of Movie Ticket: RM";
cin >> ticketPrice;
outFile << movieTitle << " " << movieTime2 << " " << hallNumber << " " << ticketPrice;
outFile.close();
inFile.close();
remove ("movieRecord.dat");
rename ("temp.dat","movieRecord.dat");
cout << "\tEdit Saved!" << endl;
system("pause");
goto adminMenu;
}
My code for reading the file:
ifstream movieCheck;
movieCheck.open("movieRecord.dat",ios::in);
movieCheck >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;
if (!movieCheck.good()){
cout << "File Open Error!" << endl;
}
while (movieCheck.read((char*)&item,sizeof(item))){
cout << "\tMovie title: " << item.movieName << endl;
cout << fixed;
cout << "\tTime: " << setprecision(2) << item.movieTime << endl;
cout << "\tHall Number: Hall " << item.hallNum << endl;
cout << "\tMovie Ticket Price: RM " << setprecision(2) << item.moviePrice << endl;
cout << "\t==============================================" << endl;
movieCheck >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;
}
movieCheck.close();
cout << endl << "\t The End of the Movie Summaries!" << endl;
When I use eof, the output will only show the first data only, simple example:
Desired Output:
Hello
Help2 \The edited record
Current Output:
Hello \does not show the edited record
When using read function however, my output is either similar to eof or it would not show at all.

How to append new data to a text file in C++ without outputting the title again?

I have a problem in outputting my code to a text file. I just wanted to print a title at the beginning of a .txt file, but it happened to end up printing along with new lines of data. Basically, I am appending new data to the text file using ios::app. How can I achieve not printing my title in the text file all over again after appending other data?
Text File Output
Here is my code btw...
#include <iostream>
#include <fstream>
#include <string>
void QuaranDiary();
struct quarantine3 //structure for QuaranDiary
{
string QuaranDiaryMonth;
string QuaranDiaryDay;
string QuaranDiaryYear;
string QuaranDiaryHour;
string QuaranDiaryMinute;
string QuaranDiaryUpdate;
};
quarantine3 diary[500];
//QuaranDiary
void QuaranDiary()
{
int i = 0, update = 0;
char QuaranDiaryMore;
do
{
cout << "=====================================================================================" << endl;
cout << " COVID-19 QUARANDIARY " << endl;
cout << "=====================================================================================" << endl << endl;
cout << "DATE (MM/DD/YYYY)" << endl << endl;
cout << "Month : ";
cin >> diary[i].QuaranDiaryMonth;
cout << "Day : ";
cin >> diary[i].QuaranDiaryDay;
cout << "Year : ";
cin >> diary[i].QuaranDiaryYear;
cout << endl;
cout << "[" << diary[i].QuaranDiaryMonth << "/" << diary[i].QuaranDiaryDay << "/" << diary[i].QuaranDiaryYear << "]" << endl << endl;
cout << "TIME (23:59)"<<endl<<endl;
cout << "Hour : ";
cin >> diary[i].QuaranDiaryHour;
cout << "Minute : ";
cin >> diary[i].QuaranDiaryMinute;
cout << endl;
cout << "[" << diary[i].QuaranDiaryHour << ":" << diary[i].QuaranDiaryMinute << "]" << endl << endl;
cout << "Health Update: ";
cin.ignore();
getline(cin, diary[i].QuaranDiaryUpdate);
update++;
cout << "\n\nAdd More to QuaranDiary? [Y/N]: ";
cin >> QuaranDiaryMore;
QuaranDiaryMore = toupper(QuaranDiaryMore);
while (toupper(QuaranDiaryMore) != 'Y' && toupper(QuaranDiaryMore) != 'N')
{
cout << "\nWrong Input. Try Again!\n" << endl;
cin.clear();
cin.ignore();
cout << "Add More to QuaranDiary? [Y/N]: ";
cin >> QuaranDiaryMore;
}
cin.clear();
cin.ignore();
system("CLS");
//fstream for QuaranDiary
ofstream QuaranDiary;
QuaranDiary.open("QuaranDiary.txt", ios::app);
QuaranDiary << "=====================================================================================" << endl;
QuaranDiary << " COVID-19 QUARANDIARY " << endl;
QuaranDiary << "=====================================================================================" << endl;;
QuaranDiary << "\nDate: " << diary[i].QuaranDiaryMonth << "/" << diary[i].QuaranDiaryDay << "/" << diary[i].QuaranDiaryYear;
QuaranDiary << "\tTime: " << diary[i].QuaranDiaryHour << ":" << diary[i].QuaranDiaryMinute << endl << endl;
QuaranDiary << "[Health Update]\n\n" << diary[i].QuaranDiaryUpdate << endl;
QuaranDiary << "=====================================================================================" << endl;
if (QuaranDiary.is_open())
{
cout << "\nCheck QuaranDiary.txt for your written health updates!" << endl;
}
else
{
cout << "\n\nUnable to Open File!" << endl;
}
QuaranDiary.close();
} while (toupper(QuaranDiaryMore == 'Y'));
}

c++ file reading into memory

i'm trying to load the file into an array when the program starts so i can
modify or search in it i don't know if my code works or not ( it's not reading the file )i have the file
and there's two books in
i have tried to debug it but couldn't find the problem the code works
but it think there's a problem with the load() function i don't know what
my code :
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
struct books{
//identfying books with all needed things
int id, status;
string title, p_name, p_address;
string date;
string aut_name, aut_nationality;
}newbook[10000], aut[10000];
int i = 0;
void load(){
ifstream myfile("books.txt", ios::in);
while (myfile >> newbook[i].id >> newbook[i].title >> newbook[i].p_name >> newbook[i].p_address >> aut[i].aut_name >> aut[i].aut_nationality >> newbook[i].date >> newbook[i].status)
i++;
}
void search_for_book(){
int temp = 0;
int idx;
cout << "enter the ID of the book you're looking for : ";
cin >> idx;
for (int srh = 0; srh < i; srh++){
if (newbook[srh].id == idx){
cout << setw(10) << "book found :" << endl;
cout << "title :" << newbook[srh].title << endl;
cout << "publisher name : " << newbook[srh].p_name << endl;
cout << "publisher address" << newbook[srh].p_address << endl;
cout << "author name :" << aut[srh].aut_name << endl;
cout << "author Nationality :" << aut[srh].aut_nationality << endl;
cout << "publish Date :" << newbook[srh].date << endl;
cout << "status :" << newbook[srh].status << endl;
temp++;
break;
}
else
srh++;
}
if (temp == 0){
cout << "couldn't find book" << endl << endl;
}
}
int main(){
load();
char choice;
cout << "enter your choice (3)";
cin >> choice;
if (choice == '3'){
search_for_book();
}
}
note :*( there are other functions like adding new book but not necessary to write )
*(i'm new to c++ don't really know how to read file into memory but i'm trying)
this is the code to save data into file :
void add_new_book_5(){
int booksnumber;
books newbook[1000], aut[100];
cout << "how many books you want to add ? ";
cin >> booksnumber;
cout << "what books you want to add :" << endl;
d_base.open(path, ios::out | ios::app);
for (int i = 0; i < booksnumber; i++){
cout << "id please : "; cin >> newbook[i].id;
cout << "title : "; cin.ignore(); getline(cin, newbook[i].title);
cout << "publisher name :"; getline(cin, newbook[i].p_name);
cout << "publisher address : "; getline(cin, newbook[i].p_address);
cout << "author" << " name : "; cin.ignore(); getline(cin, newbook[i].aut_name);
cout << "Nationality : "; getline(cin, newbook[i].aut_nationality);
cout << "Publish date :"; getline(cin, newbook[i].date);
cout << "How many copies of " << newbook[i].title << " "; cin >> newbook[i].status;
system("cls");
d_base << newbook[i].id << "\ " << newbook[i].title << "\ ";
d_base << newbook[i].p_name << "\ " << newbook[i].p_address << "\ ";
d_base << newbook[i].aut_name << "\ " << newbook[i].aut_nationality << "\ ";
d_base << newbook[i].date << "\ " << newbook[i].status << endl;
}
d_base.close();
cout << setw(76) << "Books Have Been Saved Sucessfully" << endl;
}

Item Inventory Add/Edit/View questions

Okay so i have a lot of questions for this. I was having a lot of trouble but am getting there slowly. So far I have it to where the program will read and write to a file, but it tends to repeat itself a lot. Like when reading from the file itll just keep reading the same information over and over. Also it seems to display the same record twice...and i cant test it further since it only lets me write the first record over and over without ever writing the second. Any help would be great. Also for some reason the edit function seems to pull jibberish when choosing the 1 record...so im stumped. Been working on this for hours with no luck
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
void addRecord(fstream &);
void viewRecord(fstream &);
void changeRecord(fstream &);
int menu();
const int DESC_SIZE = 21;
const int DATE_SIZE = 11;
struct inventoryData
{
char desc[DESC_SIZE]; //Desc up to 20 chars
int quantity; //Item quantity
double wholesale; //Item wholsale Cost
double retail; //Item retail Cost
char date[DATE_SIZE]; //Date able to hold info up to xx/xx/xxxx
};
int main()
{
int selection;
int recordNumber;
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
if (dataFile.fail())
{
// The file does not exist, so create it.
dataFile.open("inventory.dat", ios::out);
}
selection = menu();
while (selection != 4)
{
switch (selection)
{
case 1:
{
viewRecord(dataFile);
break;
}
case 2:
{
addRecord(dataFile);
break;
}
case 3:
{
changeRecord(dataFile);
break;
}
default:
{
cout << "Invalid - Please use 1 to 4" << endl;
break;
}
selection = menu();
}
}
dataFile.close();
return 0;
}
void addRecord(fstream &file)
{
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
inventoryData item;
cout << "Please enter the following data about the item" << endl;
cout << "Description: ";
cin.ignore();
cin.getline(item.desc, DESC_SIZE);
cout << "Quantity: ";
cin >> item.quantity;
cout << "Quantity: ";
cin >> item.quantity;
cout << "Wholesale cost: ";
cin >> item.wholesale;
cout << "Retail price: ";
cin >> item.retail;
cout << "Date (Please use MO/DA/YEAR format: ";
cin >> item.date;
dataFile.write(reinterpret_cast<char *>(&item), sizeof(item));
return;
}
void viewRecord(fstream &file)
{
string output;
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
inventoryData item;
fstream items;
char again;
dataFile.read(reinterpret_cast<char *>(&item), sizeof(item));
while (!items.eof())
{
// Display the record.
cout << "Description: " << item.desc << endl;
cout << "Quantity: " << item.quantity << endl;
cout << "Wholesale Cost: " << item.wholesale << endl;
cout << "Retail Cost: " << item.retail << endl;
cout << "Date: " << item.date << endl;
// Wait for the user to press the Enter key.
cout << "\nPress the Enter key to see the next record.\n";
cin.get(again);
// Read the next record from the file.
dataFile.read(reinterpret_cast<char *>(&item), sizeof(item));
}
}
void changeRecord(fstream &file)
{
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
inventoryData item;
int recordNumber;
cout << "Please choose a record number you want to edit" << endl;
cin >> recordNumber;
dataFile.seekg(recordNumber * sizeof(item), ios::beg);
dataFile.read(reinterpret_cast<char *>(&item), sizeof(item));
cout << "Description: " << item.desc << endl;
cout << "Quantity: " << item.quantity << endl;
cout << "Wholesale cost: " << item.wholesale << endl;
cout << "Retail price: " << item.retail << endl;
cout << "Date: " << item.date << endl;
cout << endl;
// Get the new record data.
cout << "Enter the new data:\n";
cout << "Description: ";
cin.ignore();
cin.getline(item.desc, DESC_SIZE);
cout << "Quantity: ";
cin >> item.quantity;
cout << "Quantity: ";
cin >> item.quantity;
cout << "Wholesale cost: ";
cin >> item.wholesale;
cout << "Retail price: ";
cin >> item.retail;
cout << "Date (Please use MO/DA/YEAR format: ";
cin >> item.date;
// Move back to the beginning of this record's position
dataFile.seekp(recordNumber * sizeof(item), ios::beg);
// Write new record over the current record
dataFile.write(reinterpret_cast<char *>(&item), sizeof(item));
}
int menu()
{
int menuSelection;
cout << fixed << showpoint << setprecision(2);
cout << "----------Inventory----------" << endl;
cout << "1 - View inventory" << endl;
cout << "2 - Add an item" << endl;
cout << "3 - Edit an item" << endl;
cout << "4 - End Program" << endl;
cin >> menuSelection;
if (!cin)
{
cout << "Invalid - Please use 1 to 4" << endl;
cin >> menuSelection;
}
if (menuSelection < 1 || menuSelection > 4)
{
cout << "Invalid - Please use 1 to 4" << endl;
cin >> menuSelection;
}
return menuSelection;
}
int menu()
{
int menuSelection = 0;//initialize
cout << fixed << showpoint << setprecision(2);
cout << "----------Inventory----------" << endl;
cout << "1 - View inventory" << endl;
cout << "2 - Add an item" << endl;
cout << "3 - Edit an item" << endl;
cout << "4 - End Program" << endl;
//*** flush cin, this is inside a loop, it can cause problems
cin.clear();
fflush(stdin);
cin >> menuSelection;
return menuSelection;
}
int main()
{
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
if (dataFile.fail())
{
// The file does not exist, so create it.
dataFile.open("inventory.dat", ios::out);
dataFile.close();
}
for (;;)
{
int selection = menu();
if (selection == 4)
break;
switch (selection)
{
case 1:
viewRecord(dataFile);
break;
case 2:
addRecord(dataFile);
break;
case 3:
changeRecord(dataFile);
break;
default:
cout << "Invalid - Please use 1 to 4" << endl;
break;
}
}
return 0;
}
void viewRecord(fstream &notused)
{
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
inventoryData item;
while (dataFile)
{
dataFile.read(reinterpret_cast<char*>(&item), sizeof(item));
// Display the record.
cout << "Description: " << item.desc << endl;
cout << "Quantity: " << item.quantity << endl;
cout << "Wholesale Cost: " << item.wholesale << endl;
cout << "Retail Cost: " << item.retail << endl;
cout << "Date: " << item.date << endl;
cout << endl;
}
}
void addRecord(fstream &notused)
{
fstream file("inventory.dat", ios::in | ios::out | ios::app | ios::binary);
inventoryData item;
cout << "Please enter the following data about the item" << endl;
cout << "Description: ";
cin.ignore();
cin.getline(item.desc, DESC_SIZE);
cout << "Quantity: ";
cin >> item.quantity;
cout << "Wholesale cost: ";
cin >> item.wholesale;
cout << "Retail price: ";
cin >> item.retail;
cout << "Date (Please use MO/DA/YEAR format: ";
cin.getline(item.desc, DATE_SIZE);
file.write(reinterpret_cast<char *>(&item), sizeof(item));
return;
}

Getline output won't work?

I have this code where the string info is not working as it should.
I have a getline where info is inside and it saves a hole sentence, but it won't output more than the first word.
Example:
"Hello world!"
I will only show me "hello"
Here is the part of the code:
void add() {
string name;
string faction;
string classe;
string race;
string info;
ofstream wowdatabase("wowdatabase.txt", ios::app);
cout << "Add a race or class" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "" << endl;
cout << "Enter the name of the race or class (only small letters!):" << endl;
cin >> name;
cout << "Enter Race (Type -, if writen in name section):" << endl;
cin >> race;
cout << "Enter Class (Type -, if writen in name section):" << endl;
cin >> classe;
cout << "Enter faction (Alliance/Horde):" << endl;
cin >> faction;
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
cout << "Enter the information:" << endl;
getline(cin, info);
cout << info;
system("pause");
wowdatabase << name << ' ' << faction << ' ' << classe << ' ' << race << ' ' << info << endl;
wowdatabase.close();
system("CLS");
main();
}
void searchname() {
ifstream charecter("wowdatabase.txt");
string name;
string find;
string faction;
string classe;
string race;
string info;
int i = 0;
system("CLS");
cout << "Search for a race or class" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "" << endl;
cout << "Please enter name:";
cin >> find;
while (charecter >> name >> faction >> classe >> race >> info ) {
if (find == name) {
system("CLS");
cout << "Charecter found" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "" << endl;
cout << "Name of race/class: " << name << endl;
cout << "Race: " << race << endl;
cout << "Class: " << classe << endl;
cout << "Faction: " << faction << endl;
cout << "Info: " << info << endl;
cout << "" << endl;
cout << "Press enter to return to menu" << endl;
system("pause");
system("CLS");
main();
}
}
You use variable info in several functions. For example in function searchname() you enter it as
while (charecter >> name >> faction >> classe >> race >> info )
that is in this function you do not use getline. Also your code is invalid because you may not recursively call main in C++.