Ok. I'm trying to finish writing to a file and then reading from a file but I keep getting an error when I start the void readData(void).The error is "no matching token found." What could I do to make this work/ make it easier?
I'm not understanding how to use the void function, I think. I'm sure there are more issues because when I remove void readData(void) the error moves to void writeData(void).
//Specification: Append and display records in a address database
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
ifstream infile;
string cont = "Y";
string name;
string street;
string city;
string state;
string zip;
string choice;
const char FileName[] = "TestAddress.txt";
ofstream outfile("TestAddress.txt", ios::app);
int main() {
menu();
writeData();
readData();
return 0;
} //end main
void menu(void) {
cout << "Would you like to add to the records, display them, or exit?\n";
cout << "Enter a to add, d to display, or e to exit";
cin >> choice;
}
//allow user to choose to append records, display records or exit the program
//end menu
void writeData(void) {
while (choice != "a") {
cout << "Enter the address name: ";
getline(cin, name);
cout << "Enter the house number and street: ";
cin >> street;
cout << "Enter the city: ";
cin >> city;
cout << "Enter the state: ";
cin >> state;
cout << "Enter the zip code: ";
cin >> zip;
outfile << name << "#" << street << city << "#" << state << "#" << zip << endl;
cin.ignore();
cout << "Do you want add another addressor exit? (a/e)";
getline(cin, choice);
}
outfile.close();
//Write the Address Info to a file
//loop while user still has data to write to file
//eg outStream<<name<<”#”; //where # is the delimiter
}
//end write data
void readData(void) {
//read data from a file
//use the split function to break a
//deliminated line of text into fields
infile.open("TestAddress.txt");
ifstream inMyStream("TestAddress.txt");
while (choice != "d") {
if (inMyStream.is_open()) {
//set character to use as a line between record displays
string recBreaks = "#";
recBreaks.assign(20, '#');
int fieldCount = 0; //keep track of the number of fields read
int recordCount = 1; //keep track of the number of records read
//read the first field
fieldCount = 1;
string fieldBuffer;
getline(inMyStream, fieldBuffer, '#');
while (!inMyStream.eof()) {
//display the field
switch (fieldCount) {
case 1:
cout << recBreaks << endl;
cout << "record # " << recordCount << endl;
cout << "Name...." << fieldBuffer << endl; break;
case 2:
cout << "Street.." << fieldBuffer << endl; break;
case 3:
cout << "City...." << fieldBuffer << endl; break;
case 4:
cout << "State..." << fieldBuffer << endl; break;
case 5:
cout << "Zip....." << fieldBuffer << endl;
fieldCount = 0;
recordCount++; break;
}
//read the next field
getline(inMyStream, fieldBuffer, '#');
fieldCount++;
}
cout << recBreaks << endl;
inMyStream.close();
}//end read data
}
Related
I was trying to get the user input and it should include a space because I am asking for a full name. So I used the getline method but I can't input the data correctly.
Here's the code:
#include <iostream>
#include <string>
string name, mobile, landline, work;
cout << "Enter the name of the contact to be added:";
getline(cin, name);
cout << "Enter the mobile number of this contact:";
getline(cin, mobile);
cout << "Enter the landline number of this contact:";
getline(cin, landline);
cout << "Enter the work number of this contact:";
getline(cin, work);
When I run the program this is what I get:
Enter the name of the contact to be added:Enter the mobile number of this contact:
This is the main method:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: Gaby
*
* Created on March 25, 2020, 7:14 PM
*/
#include "Contact.h"
#include "DCSList.h"
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
void showMenu();
void saveChanges(ofstream& file, DCSList& list);
/*
*
*/
int main(int argc, char** argv) {
fstream file; //This is the file we read from
ofstream outputFile; //This is the file we will write on at the end
string name, numberString; //Strings to extract the data from the file
string numbers[3]; //string array of numbers
string numberExtracted; //Used to extract each number from the numberString
string numbOfContacts; //Number of Contacts we want to read from file
int number; //Integer variable of the parsed value of the number read
int counter = 1; //Number of contacts read from file
int choice = 0; //Choice of user
DCSList list;
file.open("./ContactList.txt");
if(file.is_open()){
//If file is open then read from it
//First get the number of contacts in list
getline(file, numbOfContacts);
//Convert the number in the file to an integer
stringstream count(numbOfContacts);
//Set the value of number
count >> number;
while(counter <= number){
//Extract the name of the contact
getline(file, name);
//Extract the mobile, work and home numbers
getline(file, numberString);
//We will need to split the numberString with the - as delimiter
stringstream ss(numberString);
int i = 0; //Counter for numbers
while(getline(ss, numberExtracted, '-')){
numbers[i] = numberExtracted;
i++;
}
//Create a Contact object and add the contact to the list
Contact c(name, numbers[0], numbers[1], numbers[2]);
list.addNode(c);
counter++;
}
//Write on the other file
outputFile.open("NewContactList.txt");
if (outputFile.is_open()){
list.start();
while(list.hasNext()){
outputFile << list;
list.operator ++();
}
}
else{
cout << "File not opened!" << endl;
}
outputFile.close();
}
else{
cout << "File is not opened!" << endl;
}
file.close();
do{
showMenu();
cin >> choice;
switch(choice){
case 1:{
list.start();
while(list.hasNext()){
cout << list;
list.operator ++();
}
break;
}
case 2:
{
string name, mobile, landline, work;
cout << "Enter the name of the contact to be added:";
getline(cin, name);
cout << "Enter the mobile number of this contact:";
getline(cin, mobile);
cout << "Enter the landline number of this contact:";
getline(cin, landline);
cout << "Enter the work number of this contact:";
getline(cin, work);
//Create a contact object
Contact contact(name, mobile, work, landline);
//Add contact to list
list.addNode(contact);
}
break;
case 3:
{
string contactToDelete;
cout << "Enter a contact name or "
"any mobile, work, land number :";
cin >> contactToDelete;
if (list.deleteNode(contactToDelete)){
cout << "Contact has been deleted!" << endl;
}
}
break;
case 4:
{
string searchCriteria;
cout << "Enter a contact name or "
"any mobile, work, land number :";
getline(cin, searchCriteria);
if (list.searchNode(searchCriteria)){
cout << list;
}
else{
cout << "No contact found!" << endl;
}
break;
}
case 5:
{
cout << "Thank you for using the program." << endl;
cout << "All changes applied will be "
"saved to the output file" << endl;
//Write on the other file
outputFile.open("NewContactList.txt");
if (outputFile.is_open()) {
list.start();
while (list.hasNext()) {
outputFile << list;
list.operator++();
}
} else {
cout << "File not opened!" << endl;
}
file.close();
return 0;
}
default:{
cout << "Please enter a valid value to do an operation!" <<endl;
break;
}
}
}while(choice != 1 || choice != 2 ||
choice != 3 || choice != 4 || choice != 5);
return 0;
}
void showMenu(){
cout << "-------------PHONEBOOK-------------" << endl;
cout << "Enter a number according to "
"the operation you want to do: " << endl;
cout << "1. Show phone book" << endl;
cout << "2. Add new contact" << endl;
cout << "3. Delete a contact" << endl;
cout << "4. Search for a contact" << endl;
cout << "5. Exit program" << endl;
}
I am not able to input each value individually.
Do you know how can I fix this problem?
Thank you for your help.
How #NathanOliver has suspected you used a cin. In your main method in lines 111 and 153 (if formated in the same way as above) you can find them. Try to change them to getline() too. That should work.
This program is supposed to call a read and write function from a menu, ask for inputs, save those inputs to a file then output the data to the screen. The menu works but I can only write to the file and save the data and exit. I cannot read or output what is saved to the file. Any help with this will be greatly appreciated. I should have three working functions, main(), writeData(), and readData().
#include < iostream >
#include < fstream >
#include < string >
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
const char FileName[] = "TestAddress.txt";
string choice;
int main()
{
menu();
return 0;
}
void menu(void)
{
while (choice != "Q") {
cout << "What would you like to do?\nA. Read the existing data:\nB. Write new data to the list:\nQ.Quit\n";
cin >> choice;
if (choice == "A") {
readData();
}
else if (choice == "B") {
writeData();
}
else
break;
}
}
void writeData(void)
{
ofstream outFile("testAddress.txt");
string name;
string street;
string city;
string state;
int zip;
string cont = "y";
ifstream inFile;
while (cont != "q") {
cout << "Please enter the name:\n";
getline(cin, name);
cout << "Please enter the street:\n";
getline(cin, street);
cout << "Please enter the city:\n";
getline(cin, city);
cout << "Please enter the state:\n";
getline(cin, state);
cout << "Please enter the zip code:\n";
cin >> zip;
outFile << name << street << "#" << city << state << zip << endl;
cin.ignore();
cout << "Would you like to continue? Type q to quit:";
getline(cin, cont);
cin.ignore();
}
outFile.close();
inFile.open("testAddress.txt");
string fieldBuffer;
if (inFile.is_open()) {
while (inFile.eof()) {
getline(inFile, fieldBuffer, ',');
cout << fieldBuffer;
cout << endl;
}
}
}
//use # sign for delimiter
void readData(void)
{
ifstream inMyStream(FileName);
if (inMyStream.is_open()) {
string recBreaks = "";
recBreaks.assign(20, '*');
int fieldCount = 0;
int recordCount = 1;
fieldCount = 1;
string fieldBuffer;
getline(inMyStream, fieldBuffer, '#');
while (inMyStream.eof()) {
switch (fieldCount) {
case 1:
cout << recBreaks << endl;
cout << "Record #" << recordCount << endl;
cout << "Name...." << fieldBuffer << endl;
break;
case 2:
cout << "Street...." << fieldBuffer << endl;
break;
case 3:
cout << "City...." << fieldBuffer << endl;
break;
case 4:
cout << "State...." << endl;
break;
case 5:
cout << "Zip Code...." << endl;
fieldCount = 0;
recordCount++;
break;
getline(inMyStream, fieldBuffer, '#');
fieldCount++;
}
cout << recBreaks << endl;
inMyStream.close();
}
}
}
I have fixed a number of errors in this code, THANX to all who commented! Everything is working now except the readData function. When I input data to the file and run the readData function I get an infinite loop. Is there a break statement out of place?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
const char FileName[] = "TestAddress.txt";
string choice;
int main()
{
menu();
return 0;
}
void menu(void)
{
while (choice != "Q")
{
cout << "What would you like to do?\nA. Read the existing data:\nB. Write new data to the list:\nQ.Quit\n";
cin >> choice;
if (choice == "A")
{
readData();
}
else if (choice == "B")
{
writeData();
}
else
break;
}
}
void writeData(void)
{
ofstream outFile("TestAddress.txt");
string name;
string street;
string city;
string state;
int zip;
string cont = "y";
ifstream inFile;
while (cont != "q")
{
cout << "Please enter the name:\n";
cin.ignore();
getline(cin, name);
cout << "Please enter the street:\n";
getline(cin, street);
cout << "Please enter the city:\n";
getline(cin, city);
cout << "Please enter the state:\n";
getline(cin, state);
cout << "Please enter the zip code:\n";
cin >> zip;
outFile << name<< "#" << street<< "#"<< city << "#" << state << "#" << zip << "#" << endl;
cin.ignore();
cout << "Would you like to continue? Type q to quit:";
getline(cin, cont);
cin.ignore();
}
outFile.close();
inFile.open("TestAddress.txt");
string fieldBuffer;
if (inFile.is_open())
{
while (!inFile.eof())
{
getline(inFile, fieldBuffer, '#');
cout << fieldBuffer;
cout << endl;
}
}
}
//use # sign for delimiter
void readData(void)
{
ifstream inMyStream(FileName);
if (inMyStream.is_open())
{
string recBreaks = "";
recBreaks.assign(20, '*');
int fieldCount = 0;
int recordCount = 1;
fieldCount = 1;
string fieldBuffer;
getline(inMyStream, fieldBuffer, '#');
while (!inMyStream.eof())
{
switch (fieldCount)
{
case 1:
cout << recBreaks << endl;
cout << "Record #" << recordCount << endl;
cout << "Name...." << fieldBuffer << endl;
break;
case 2:
cout << "Street...." << fieldBuffer << endl;
break;
case 3:
cout << "City...." << fieldBuffer << endl;
break;
case 4:
cout << "State...." << fieldBuffer << endl;
break;
case 5:
cout << "Zip Code...." << fieldBuffer << endl;
fieldCount = 0;
recordCount++;
break;
getline(inMyStream, fieldBuffer, '#');
fieldCount++;
}
cout << recBreaks << endl;
inMyStream.close();
}
}
}
Hello I am having issues with a final project. The objective is to have the user create a form that allows a user to view data, edit data, add data, and save their password data in an encoded format. The program starts with an input file made by the user. The delimiter is ';', and the first char is a "code", then the, site, username, password, and notes follow.
I am very new to vectors, and I am not allowed to use a 2d array, or map.
Thank you for your time.
#include <iomanip>
#include <cmath>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
const int MAX_SIZE = 30;
const int BUFFER_SIZE = 200;
struct dataRow {
string site, user, pass, notes;
string code;
};
string inFileName; //name of inputfile
string outFileName;
ifstream pathStream;
ofstream outFile;
char inputChar;
int extPosition(1), count = 0,lineNum;
void displayVector(vector<dataRow> inputData);
void viewLineData(vector<dataRow> inputData, int lineNum);
void addNewRow(vector<dataRow> inputData,int& lastRowNum, string site, string user, string pass, string notes);
void editLineData(vector<dataRow> inputData, int& lineNum, string site, string user, string pass, string notes);
void warning();
void cleanBuffer();
bool displayMenu();
int exit();
dataRow descripLine;
int main()
{
vector<dataRow> inputData;
string rowDescripin,userin,passin,notesin,sitein;
string codein,errorMsg;
int lastRow;
//add a .txt extension to the file if the user didn't provide an extension
if (inFileName.size() > 4)
// If there's a valid extension, it will be in the last 4 positions of the string; Adjust by 1 for 0 offset
extPosition = inFileName.size() - 4;
int ext = inFileName.find_last_of(".txt");
if (!(inFileName.find_last_of(".") == extPosition))
{
inFileName += ".txt";
}
cout << "\nPlease enter the filename of input file: ";
cin >> inFileName;
pathStream.open(inFileName.c_str());
if (pathStream.fail())
{
cerr << inFileName << " failed to open.\n";
system("pause");
exit(1);
}
else
{
cout << "startup success" << endl;
}
getline(pathStream, codein, ';');
descripLine.code = codein;
while (!pathStream.eof())
{
getline(pathStream, sitein, ';');
descripLine.site = sitein;
getline(pathStream, userin, ';');
descripLine.user = userin;
getline(pathStream, passin, ';');
descripLine.pass = passin;
getline(pathStream, notesin, ';');
descripLine.notes = notesin;
inputData.push_back(descripLine);
}
displayVector(inputData);
displayMenu();
while (cin){
cin >> inputChar;
inputChar = toupper(inputChar);
//Adjust calculations based on inputCHar
if (inputChar == 'D') // Display line descriptions
{
displayVector(inputData);
}
else if (inputChar == 'V') //View line data
{
cout << "Enter line number you wish to view: ";
cin >> lineNum;
viewLineData(inputData, lineNum);
}
/* else if (inputChar == 'E') //Edit line Data
{
cout << "Enter line number you wish to edit: ";
cin >> lineNum;
editLineData(inputData, lineNum);
}*/
else if (inputChar == 'A') //Add line data
{
warning();
lastRow = inputData.size();
cout << "Enter a line description: ";
cin >> rowDescripin;
cout << "Enter a line username: ";
cin >> userin;
cout << "Enter a line password: ";
cin>>passin;
cout << "Enter notes: ";
cin>>notesin;
addNewRow(inputData, lastRow, rowDescripin, userin, passin, notesin);
}
/*else if (inputChar == 'S') //Save and encode file
{
}*/
else if (inputChar == 'X') //exit program
{
exit();
}
}
system("pause");
}
bool displayMenu()
{
cout << endl << " AVAILABLE OPTIONS " << endl << endl <<
"D - DISPLAY LINE DESCRIPTIONS" << endl <<
"V - VIEW LINE DATA" << endl <<
"E - EDIT LINE DATA" << endl <<
"A - ADD LINE DATA" << endl <<
"S - SAVE AND ENCODE FILE" << endl <<
"X - EXIT PROGRAM" << endl;
return 0;
}
void viewLineData(vector<dataRow> inputData,int lineNum)
{
cout << inputData[lineNum].site << endl << inputData[lineNum].user<<endl<<inputData[lineNum].pass <<endl<<inputData[lineNum].notes;
}
void displayVector(vector<dataRow> inputData)
{
cout << fixed << setprecision(3);
for (unsigned int i = 0; i < inputData.size(); i++)
{
cout << left << setw(20) << inputData[i].site ;
}
}
void addNewRow(vector<dataRow> inputData, int& lastRowNum, string site, string user, string pass, string notes)
{
char ans;
cout << "You have entered:" << endl << site << endl << user << endl << pass << endl << notes<<endl;
cout << "Is this the data you wish to add (Y/N)? ";
cin >> ans;
ans = toupper(ans);
if (ans == 'Y')
{
dataRow tempRow = { site, user, pass, notes };
inputData.push_back(tempRow);
cout << inputData.size();
int num = inputData.size()-1;
for (unsigned int i = 0; i < inputData.size(); i++)
{
cout << inputData[i].site << endl << inputData[i].user << endl << inputData[i].pass << endl << inputData[i].notes;
}
}
else if (ans == 'N')
{
cout << "ok enter of no";
}
}
void warning()
{
cout<< "WARNING: You cannot use semi-colons in these fields. Any semi-colons entered will be removed." << endl;
return;
}
int exit()
{
pathStream.close();
system("pause");
return 0;
}
void cleanBuffer()
{
cin.clear();
cin.ignore(BUFFER_SIZE, '\n');
}
I have got an assignment project to make a program using C++ which maintains a list of Students (their name, age, and GPA) in a text file. The program has the following functionality:
Insertion of record
Deletion of record
Searching of record
Updating a record
When deleting a record my code takes a string name as input and removes it from the text file. However the next two lines in the file (age & gpa for that student) are left. How do I remove those too?
Following is the code for my program.
#include <iostream>
#include <fstream>
using namespace std;
void writing();
void deleting();
void searching();
class student {
public:
int age = 0;
string name;
void SetGpa(float x)
{
gpa = x;
}
float GetGpa()
{
return gpa;
}
private:
float gpa = 0.0;
};
int main()
{
int opt;
cout << "Please Enter an option number to continue:\n ";
cout << "\nPress 1 for New Record insertion";
cout << "\nPress 2 for Record Deletion";
cout << "\nPress 3 for Searching a Record";
cout << "\nPress 4 for Updating a Record";
cout << "\nEnter option Number: ";
cin >> opt;
switch (opt)
{
case 1:
{
writing();
break;
}
case 2:
{
deleting();
break;
}
case 3:
{
searching();
break;
}
case 4:
{
deleting();
writing();
cout << "Record has been updated! ";
break;
}
}
}
void writing()
{
float a;
student moiz;
cout << "Please enter name of student: ";
cin >> moiz.name;
cout << "Please enter the age of student: ";
cin >> moiz.age;
cout << "Pleae enter the Gpa of student: ";
cin >> a;
moiz.SetGpa(a);
ofstream myfile;
myfile.open("record.txt", ios::app | ios::out);
myfile << endl << moiz.name << endl;
myfile << moiz.age << endl;
myfile << moiz.GetGpa();
myfile.close();
}
void deleting()
{
string line, name;
cout << "Please Enter the name of record you want to delete: ";
cin >> name;
ifstream myfile;
ofstream temp;
myfile.open("record.txt");
temp.open("temp.txt");
while (getline(myfile, line))
{
if (line != name)
temp << line << endl;
}
cout << "The record with the name " << name << " has been deleted if it exsisted" << endl;
myfile.close();
temp.close();
remove("record.txt");
rename("temp.txt", "record.txt");
}
void searching()
{
ifstream fileInput;
fileInput.open("record.txt");
string line, search;
cout << "Please enter the term to search: ";
cin >> search;
for (unsigned int curLine = 0; getline(fileInput, line); curLine++)
{
if (line.find(search) != string::npos)
{
cout << "found: " << search << " on line: " << curLine << endl;
}
else
{
cout << "Error! Not found on Line" << curLine << endl;
}
}
}
You can add an else clause to your statement checking the name, and introduce a counter of how many of the following lines should be skipped after name was found:
int skip = 0;
while (getline(myfile, line)) {
if ((line != name) && !(skip > 0)) {
temp << line << endl;
}
else {
if(skip == 0) {
skip = 2; // Skip the next two lines also
}
else {
--skip;
}
}
}
thanks for your anticipated help. I have been looking at this code for hours and days but I just cant seem to find out why my delRecFunc() isn't deleting just one record at a time. It appears it is deleting the whole file.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iomanip>
using namespace std;
const int NAME_SIZE = 40, ADDR_SIZE = 50, PHONE_SIZE = 14;
char y, Y;
struct Info
{
char name[NAME_SIZE];
int age;
char address1[ADDR_SIZE];
char phone[PHONE_SIZE];
}people;
void popFunc();
void dispFunc();
void appFunc();
void delRecFunc();
void searchFunc();
void modRecFunc();
int getNumRec();
int validateRecord (int);
void wipeFunc();
int main()
{
Info person;
char choice, option;
cout << " The file we are working with is named stuff.dat,\n"
<< "I will let you know if it unavailable " << endl;
cout << " "<< endl;
do
{
cout << " \n \n Simple People Records... \n \n \n "
<< " Please choose from the following options: \n \n \n"
<< " 1. POPULATE THE BINARY FILE \n"
<< " 2. DISPLAY THE CONTENTS OF THE FILE\n"
<< " 3. APPEND A RECORD TO THE FILE\n"
<< " 4. DELETE A RECORD FROM THE FILE\n"
<< " 5. SEARCH FOR A CERTAIN RECORD\n"
<< " 6. MODIFY A CERTAIN RECORD. \n"
<< " 7. WIPE OUT THE ENTIRE CONTENTS OF THE FILE. \n" <<endl;
cin >> option;
switch(option)
{
case '1': popFunc();
system("pause");
break;
case '2': dispFunc();
break;
case '3': appFunc();
break;
case '4': delRecFunc();
break;
case '5':searchFunc();
break;
case '6':modRecFunc();
break;
case '7':wipeFunc();
break;
}
}
while(choice!= 1000);
system("pause");
return(0);
}
void popFunc()
{ fstream file("stuff.dat", ios::out | ios::binary);
if (file.fail())
{
cout << "the file does not exist so we are creating it now... ";
system("pause");
file.open("stuff.dat", ios::out);
}
cout << "enter the following data about a person: "<<endl;
cout << "Name: " <<endl;
cin >> ws;
cin.getline(people.name,NAME_SIZE);
cout << "Age (integers only or the program will be corrupted): " <<endl;
cin >> people.age;
cin.ignore(); //skip over the remaining newline.
cout<< "Address line 1: ";
cin >> ws;
cin.getline(people.address1,ADDR_SIZE);
cout << "Phone: in the following format ie: 201.123.1234 (no hyphens)";
cin >> ws;
cin.getline(people.phone,PHONE_SIZE);
file.write(reinterpret_cast<char *>(&people), sizeof(people));
file.close();
}
void dispFunc()
{
ifstream file;
file.open("stuff.dat", ios::binary);
if (file.fail())
{
cout << "the file does not exist so we are creating it now... ";
system("pause");
file.open("stuff.dat", ios::out);
}
while(file.read(reinterpret_cast<char *> (&people), sizeof(people)))
{
cout << "Name: "<< people.name <<endl;
cout << "Age: "<< people.age <<endl;
cout << "Address: " <<people.address1 <<endl;
cout << "Phone #: " <<people.phone << " \n\n"<<endl;
}
file.close();
}
void appFunc()
{ ofstream file;
file.open("stuff.dat", ios::binary | ios::app);
if (file.fail())
{
cout << "the file does not exist so we are creating it now... ";
system("pause");
file.open("stuff.dat", ios::out);
}
cout << "Name: " <<endl;
cin >> ws;
cin.getline(people.name,NAME_SIZE);
cout << "Age (integers only or the program will be corrupted): " <<endl;
cin >> people.age;
cin.ignore(); //skip over the remaining newline.
cout<< "Address line 1: ";
cin >> ws;
cin.getline(people.address1,ADDR_SIZE);
cout << "Phone: Phone: in the following format ie: 201.123.1234 (no hyphens)";
cin >> ws;
cin.getline(people.phone,PHONE_SIZE);
file.write(reinterpret_cast<char *>(&people), sizeof(people));
file.close();
}
void searchFunc()
{
int count =1;
int answer;
long recNum;
int recCount = getNumRec();
fstream search;
search.open("stuff.dat", ios::in | ios:: binary);
cout << " Please enter 1 - " <<recCount ;
cout << " and I will display the data /n"<<endl;
cin >>recNum;
while(recNum<1 || recNum > recCount)
{
cout<<"Please enter a number between 1 and "<<recCount<<": ";
cin>>recNum;
}
answer = validateRecord(recNum);
}
void modRecFunc()
{
int count=1;
int answer;//to hold choice from the user
long recNum;//to hold a record number
int recCount = getNumRec();//variable to hold how many record the file has
fstream search;
//open file
search.open("stuff.dat",ios::in|ios::out|ios::binary);
cout<<"Which record do you wish to edit? ";
cin>>recNum;//variable to store the record the user wish to delete
//validation so the user is not allow to enter more numbers than the actual
//size of the file
while(recNum<1||recNum>recCount)
{
cout<<"Please enter a number between 1 and "<<recCount<<": ";
cin>>recNum;
}
//move pointer to desire position
cout<<endl;
answer= validateRecord(recNum);//make sure the record is the right one
cout<<endl;
if(answer==1)
{
//get the new data
cout << "Name: " <<endl;
cin >> ws;
cin.getline(people.name,NAME_SIZE);
cout << "Age (integers only or the program will be corrupted): " <<endl;
cin >> people.age;
cin.ignore(); //skip over the remaining newline.
cout<< "Address line 1: ";
cin >> ws;
cin.getline(people.address1,ADDR_SIZE);
cout << "Phone: Phone: in the following format ie: 201.123.1234 (no hyphens)";
cin >> ws;
cin.getline(people.phone,PHONE_SIZE);
search.seekp((recNum-1)*sizeof(people), ios::beg);
search.write(reinterpret_cast<char *>(&people), sizeof(people));
}
cout<<endl;
search.close();
}
void wipeFunc()
{ char option;
ofstream file;
cout << "This option will delete all the contents of the file "<<endl;
cout << " Are you sure you want to delete the file? Y or N " <<endl;
cin >> option;
if (option == 'y' || option == 'Y')
{
cout << " Warning, if you hit Y, you will lose everything " <<endl;
cout << " Y to confirm, N to return to main menu" <<endl;
cin >> option;
if(option == 'y' || option == 'Y')
{
file.open("stuff.dat", ios::out | ios::binary);
file.close();
}
}
}
int validateRecord (int recNum)
{
int answer;// variable to hold the answer from the user
fstream validate;
//open file
validate.open("stuff.dat",ios::in|ios::out|ios::binary);
validate.seekg((recNum-1)*sizeof(people));
//read record from file
validate.read(reinterpret_cast<char*>(&people),sizeof(people));
cout<<endl;
cout << "the name is "<< people.name <<endl;
cout << "the age is "<< people.age <<endl;
cout << "the address is" <<people.address1 <<endl;
cout << "the phone is Phone: " <<people.phone <<endl;
cout<<"Is this the file you want?\n"
"1. yes\n"
"2. no\n"
"Choice: ";
cin>>answer;
// validate answer to 1 or 2
while(answer<1||answer>2)
{
cout<<"enter only 1 or 2: ";
cin>>answer;
}
cout<<endl;
validate.close();
return answer;
}
int getNumRec()
{
int count =0;
fstream file;
file.open("stuff.dat", ios::in|ios::binary);
if (file.fail())
{
cout << "Error opening file. Program aborting.\n";
}
file.read(reinterpret_cast<char *>(&people),sizeof(people));
while (!file.eof())
{
count++;
file.read(reinterpret_cast<char *>(&people),
sizeof(people));
}
file.close();//close the file
return count;//return count the erase function
}
void delRecFunc()
{
int count=1;
int answer; //to hold choice from the user
double recNum;//to hold the record number the user wishes to delete
int recCount = getNumRec();//variable to hold how many record the file has
fstream erase;
erase.open("stuff.dat", ios::in|ios::out|ios::binary);
Info Temp; //*****NEW TEMP STRUCT VAR*****//
cout << "Please enter the phone number of the person you want to delete in this
format 201.123.1111)";
cin >> recNum;
//move pointer to desire position
erase.seekg((recNum-1)*sizeof(people));
//read record from file
erase.read(reinterpret_cast<char*>(&people),sizeof(people)); //read record from file
//get answer from the validateRecord function
answer = validateRecord (recNum);
if(answer == 1)
{
ofstream copy;
copy.open("stuff2.dat", ios::out | ios::binary);
erase.seekg(0*sizeof(people)); // Move pointer to beginning of the file
erase.read(reinterpret_cast<char*>(&people),sizeof(people));
// BEGIN NEW CODE //
// Keep looping till there are no more records in the customer.dat file
while (!erase.eof())
{
// If the id that the user wants deleted doesnt match the current
// records id, copy it to the temp directory
if(people.phone != Temp.phone)
{
// Write the record to copy.dat
copy.write(reinterpret_cast<char*>(&people),sizeof(Info));
}
// Read the next line from customer.dat
erase.read(reinterpret_cast<char*>(&people),sizeof(Info));
}
// Close both files
erase.close();
copy.close();
}
// Delete the Old customer.dat file
remove("stuff.dat");
// Rename the temporary holder to "customer.dat"
rename("stuff2.dat","stuff.dat");
}
You're taking an improperly formatted double (inputted from the cin >> recNum), seeking that far (*sizeof(people) into the file, and going from there. Seems like you need to start there.
Looks like you are entering the phone number in recNum (in the format 201.123.1111) and doing a seekg, which will give incorrect results