Stuck on project - c++

I have an assignment in my c++ class which is: Write a program that declares a struct to store the data of a football player (player’s name, player’s position, number of touchdowns, number of catches, number of passing yards, number of receiving yards, and the number of rushing yards). Declare an array of 10 components to store the data of 10 football players. Your program must contain a function to input data from a file (You will need to create the input file) and functions to output data to the console. Add functions to search the array to find the index of a specific player, and update the data of a player. Before the program terminates, give the user the option to save data in a file (write a function for this). Your program should be menu driven, giving the user various choices. Your main function should mostly have variable declarations and function calls in it. Most operations should be handled by other functions.
I am stuck on getting my program to read the info on my input file. please help
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
struct player {
string name;
string position;
int touchdowns;
int catches;
int pass;
int receive;
int rush;
};
int addData( ifstream& ifile, int count , player football[])
{
if (count == 0)
{
ifile >> football[count].name;
ifile >> football[count].position;
ifile >> football[count].touchdowns;
ifile >> football[count].catches;
ifile >> football[count].pass;
ifile >> football[count].receive;
ifile >> football[count].rush;
count++;
}
else if (count != 0)
{
int i = 0;
string name;
string position;
int touchdowns;
int catches;
int pass;
int receive;
int rush;
while (i != -1)
{
ifile >> name >> position >> touchdowns >> catches >> pass >> receive >> rush;
if((*(&football + 1) - football) > 0)
{
if (name == football[i].name)
{
i++;
}
if (name != football[i].name)
{
football[count].name = name;
football[count].position = position;
football[count].touchdowns = touchdowns;
football[count].catches = catches;
football[count].pass = pass;
football[count].receive = receive;
football[count].rush = rush;
i = -1;
count++;
}
}
}
}
return count;
}
void display(int count, player football[])
{
cout << "There are " << count << " players," << endl;
if (count <= 0)
{
cout << "No players to display. ";
}
else
{
for (int i = 0; i < count;i++)
{
cout << i + 1 <<". " << football[i].name << endl;
cout << "Position: " << football[i].position << endl;
cout << "Touchdowns: " << football[i].touchdowns << endl;
cout << "Catches: " << football[i].catches << endl;
cout << "Passes: " << football[i].pass << endl;
cout << "Receiving Yards: " << football[i].receive << endl;
cout << "Rushing Yards: " << football[i].rush << endl;
}
}
}
void findandUpdate(string search, int count, player football[])
{
string name;
string position;
int touchdowns;
int catches;
int pass;
int receive;
int rush;
bool found = false;
for (int i = 0; i < count; i++)
{
if (search == football[i].name)
{
found = true;
cout << "Searched player is at index " << i + 1 << endl;
cout << "You may now update the player's name, player's position, number of touchdowns, number of catches,"
<< "number of passing yards, number of receiving yards, and the number of rushing yards \n";
cout << "Name: "; cin >> name;
cout << "Position: "; cin >> position;
cout << "Touchdowns: "; cin >> touchdowns;
cout << "Catches: "; cin >> catches;
cout << "Passes: "; cin >> pass;
cout << "Received: "; cin >> receive;
cout << "Rushed: "; cin >> rush;
football[i].name = name;
football[i].position = position;
football[i].touchdowns = touchdowns;
football[i].catches = catches;
football[i].pass = pass;
football[i].receive = receive;
football[i].rush = rush;
}
}
if (found == false)
{
cout << "No results.";
}
}
int main()
{
cout << "Press 1 to add a player.\nPress 2 to display players.\nPress 3 to find a player.\nPress 4 to update player information.\nPress 5 to save data.\n";
int x = 0;
cin >> x;
ifstream ifile;
player football[10];
ifile.open("footballplayers.txt");
int i = 0;
int count = 0;
while (i != -1)
{
switch (x)
{
case 1:
{
count = addData(ifile, count, football);
}
break;
case 2: display(count, football);
break;
case 3:
{
string name;
cout << "Enter football player name: ";
cin >> name;
findandUpdate(name,count, football);
}
break;
default: i = -1;
}
}
ifile.close();
string answer;
cout << "Save data? Type yes or no.";
cin >> answer;
if (answer == "yes")
{
ofstream ofile;
ofile.open("SavePlayerData.txt");
for (int i = 0; i < count; i++) {
ofile << football[i].name + " ";
ofile << football[i].name + " ";
ofile << football[i].position + " ";
ofile << football[i].touchdowns + " ";
ofile << football[i].catches + " ";
ofile << football[i].pass + " ";
ofile << football[i].receive + " ";
ofile << football[i].rush + " ";
ofile << "\n";
}
ofile.close();
}
}
Input file:
George RB 12 5 0 47 578
Brett QB 5 0 2017 0 44
Peyton WR 3 15 0 246 12
Logan WR 2 7 0 89 6
Nolan WR 1 2 3 0 0
John TE 5 17 0 402 0
Brandon QB 4 0 310 0 0
Dalton RB 1 2 43 5
Justin WR 1 10 0 441 0
Mason WR 0 2 0 12 0

your basic logic does not do as asked in the specs. First thing it should do is read the file, before asking for any input from a menu. You have tried to create a strange hybrid of reading the file and interactively adding a player (which is not part of the requirements)
So simplify and get it so that you read the whole file in a function called 'loadFile' and then print the whole thing out (like your option 2).
Get those things going first then add the menu to ask for modify, find and print

Related

Im having trouble with this assignment that has me write vectors and arrays to a file

So in this assignment I have to have one function that has the user enter the vector which is the driver name and then they enter the drivers 4 points. That function is fine. I also Have to do a second function that writes the name and the average that I get from the 4 points to the txt file. and then display the name and averages in main. Right now I am stuck on the second function because I'm having trouble getting it to where it would write the vector and then the average after it. right now it is writing both vector elements and then the first average, and then both vector elements and the second average. can someone help me
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
#include <fstream>
using namespace std;
//function prototypes
void Enter_Driver_Data(vector<string> &driverName, int points[8][4], string fileName, fstream& file, int& counter);
void Calculate_Average(vector<string> &driverName, int points[8][4], string fileName, fstream& file, int& counter);
int main()
{
int counter = 0;//this counter is for the average function
int points[8][4];
vector<string>driverName;
fstream file;
string fileName;
int average;
//user will enter a text file name
cout << "Please enter the file name: ";
getline(cin, fileName);
Enter_Driver_Data(driverName, points, fileName, file, counter);
Calculate_Average(driverName, points, fileName, file, counter);
cout << setprecision(1) << fixed << endl;
fstream txtInput(fileName, ios::in);
//outputting the txt file data
for (string i : driverName)
{
cout << i << "'s average points is: ";
txtInput >> average;
cout << endl;
}
cout << endl << endl;
system("pause");
return 0;
}
void Enter_Driver_Data(vector<string> &driverName, int points[8][4], string fileName, fstream& file, int& counter)//this function is for entering data
{
file.open(fileName, ios::out);
string driverNameInput;
//filestream declarations
fstream txtOutput(fileName, ios::out);
//again declaration
bool again = true;
//for loop for data
for (int name = 0; name < 8 && again; name++)//name is for the row of the array
{
cout << "\nPlease enter the driver's name: ";
getline(cin, driverNameInput);
driverName.push_back(driverNameInput);
txtOutput << driverName[name] << ": ";
for (int score = 0; score < 4; score++)//score is for the column of the array
{
cout << "\nPlease enter " << driverName[name] << "'s score number " << score + 1 << ": ";
cin >> points[name][score];
while (points[name][score] != 60 && points[name][score] != 70 && points[name][score] != 80 && points[name][score] != 90 && points[name][score] != 100)
{
cout << "Your input was invalid: please enter the scores which are 60, 70, 80, 90,or 100: ";
cin >> points[name][score];
}
cout << points[name][score] << endl;
txtOutput << points[name][score] << " ";
cin.ignore();
cin.clear();
}
txtOutput << endl;
cout << "Would you like to enter another driver?(1 for yes and 0 for no): ";
cin >> again;
cin.ignore();
cin.clear();
counter++;
}
file.close();
}
void Calculate_Average(vector<string> &driverName, int points[8][4], string fileName, fstream& file, int& counter)
{
file.open(fileName, ios::app);
fstream txtOutput(fileName, ios::app);
double totalBeforeAverage, average;
vector <double> avg;
for (int name = 0; name < counter; name++)
{
totalBeforeAverage = 0, average = 0;
for (int score = 0; score < 4; score++)
{
totalBeforeAverage += points[name][score];
}
average = totalBeforeAverage / 4;
avg.push_back(average);
}
for (string drivName : driverName)
{
txtOutput << drivName << ": ";
}
for (double averageToFile : avg)
{
txtOutput << averageToFile << endl;
}
file.close();
}

How do I search the structure?

I'm not quite getting a structure search. I have a task, I need to search for students by full name, year of birth, group number or course number. I can search by group number or course number, but the search by full name and date of birth is problematic.
Here are my code and my input file. (I'm sorry if my code is unprofessional, I'm just learning and I need to pass this task, but I'm having no luck and I have no one to turn to for help)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Student
{
string name;
string yearob;
int course;
int group;
};
ostream& operator<<(ostream& out, const Student obj)
{
out << obj.name << " " << obj.yearob << " " << obj.group << " " << obj.course;
return out;
}
int main()
{
setlocale(LC_ALL, "");
int search = 0;
string name_s, yearob_s;
int course_s, group_s;
int chek = 1;
while (chek == 1)
{
cout << "Enter 1 to start, 0 to exit > ";
cin >> chek;
switch (chek)
{
case(0):
break;
case(1):
{
int leng = 0;
string s;
ifstream fle("input.txt");
while (getline(fle, s))
{
leng += 1;
}
Student* list = new Student[leng];
int a = 0;
fle.close();
ifstream file("input.txt");
string ss, buff;
while (getline(file, s))
{
buff.assign(s);
list[a].course = buff[0] - '0';
buff.erase(0, 2);
ss += buff[0];
ss += buff[1];
list[a].group = stoi(ss);
ss.clear();
buff.erase(0, 3);
for (int i = 0; i < 4; i++)
list[a].yearob += buff[i];
buff.erase(0, 5);
list[a].name.assign(buff);
a += 1;
buff.clear();
}
cout << "What parameter should be used to find students: 1 - by name, 2 - by year of birth, 3 - by course, 4 - by group number: ";
cin >> search;
switch (search) {
case(1):
cin >> name_s;
for (int i = 0; i <= leng; i++) {
if (list[i].name.find(name_s, 10)) {
cout << list[i].name << ", " << list[i].course << " course, " << list[i].group << " group, " << list[i].yearob << " year of birth; " << endl;
}
else {
continue;
}
}
case(2):
cin >> yearob_s;
for (int i = 0; i <= leng; i++) {
if (list[i].yearob.find(yearob_s, 5)) {
cout << list[i].name << ", " << list[i].course << " course, " << list[i].group << " group, " << list[i].yearob << " year of birth; " << endl;
}
else {
continue;
}
}
case(3): {
cin >> course_s;
for (int i = 0; i <= leng; i++) {
if (course_s == list[i].course) {
cout << list[i].name << ", " << list[i].course << " course, " << list[i].group << " group, " << list[i].yearob << " year of birth; " << endl;
}
else {
continue;
}
}
}
case(4):
cin >> group_s;
for (int i = 0; i <= leng; i++) {
if (group_s == list[i].group) {
cout << list[i].name << ", " << list[i].course << " course, " << list[i].group << " group, " << list[i].yearob << " year of birth; " << endl;
}
else {
continue;
}
}
}
file.close();
continue;
}
default:
{
cout << "Input error" << endl;
continue;
}
}
}
}
Input file:
2 01 1999 Cody Hoyt
2 01 2002 Danielle Robyn Diaz
3 01 1999 Mayra Marie Collins
2 05 2000 Marc Nunez
4 05 2000 Tricia Gilmore
5 04 2001 Dale Lucas
1 01 1998 Ruby Merritt
2 01 2001 Tabitha Jenkins
4 02 1995 George Kris Oneill
2 03 1999 Bonnie Blair
Just maybe a shorter version of your code. I provide it not as a solution to your main question (because the following code is pretty advanced), but as an example of how you could avoid repeating code and making big nested constructions.
Here I moved out the code of reading students from a file into a separate function, and inside it should easily read each student using operator>> from a file. Similarly you can define operator<< to specify in which format you want students to be printed.
The repetitive code of printing filtered students is moved into a single function, that iterates all students and prints only pass a given test. You then give this test as a lambda function in each branch of switch operator
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <functional>
using namespace std;
struct Student
{
string name;
string yearob;
int course;
int group;
};
ostream& operator<<(ostream& out, const Student& stud)
{
out << stud.name << ", " << stud.course << " course, " << stud.group << " group, " << stud.yearob << " year of birth; " << endl;
return out;
}
istream& operator>>(istream& in, Student& stud)
{
in >> stud.course >> stud.group >> stud.yearob >> stud.name;
return in;
}
vector<Student> read_students_file(const string& filename) {
vector<Student> students;
ifstream file(filename);
while (file)
{
students.push_back({}); // insert empty student
file >> students[students.size() - 1]; // fill student
}
file.close();
return students ;
}
void print_filtered(const vector<Student>& students, function<bool(const Student&)> should_print) {
for (const Student& student : students) {
if (should_print(student)) {
cout << student;
}
}
}
int main()
{
setlocale(LC_ALL, "");
while (true)
{
cout << "Enter 1 to start, 0 to exit > ";
int check;
cin >> check;
if (check == 0) {
break;
} else if (check != 1) {
continue;
}
vector<Student> students = read_students_file("input.txt");
cout << "What parameter should be used to find students: 1 - by name, 2 - by year of birth, 3 - by course, 4 - by group number: ";
int search_variant;
cin >> search_variant;
switch (search_variant) {
case(1): {
string find_name;
cin >> find_name;
print_filtered(students,
[&](auto& student){ return student.name == find_name; });
break;
}
case(2): {
string find_yearob;
cin >> find_yearob;
print_filtered(students,
[&](auto& student){ return student.yearob == find_yearob; });
break;
}
case(3): {
int find_course;
cin >> find_course;
print_filtered(students,
[&](auto& student){ return student.course == find_course; });
break;
}
case(4): {
int find_group;
cin >> find_group;
print_filtered(students,
[&](auto& student){ return student.group == find_group; });
break;
}
default: {
cout << "Input error" << endl;
continue;
}
}
}
}

My function don't take over the variable value from other function

I have a program to create a phone book in a file. Some of my functions don't work or don't work properly.
user.h
#pragma once
#include <string>
#include <vector>
using namespace std;
class User
{private:
string firstname, lastname, country, city, street;
string phone;
public:
string prefix;
void ReadAllUsers(User[], int&);
void SaveUser(User, int&);
void SaveToFile(const User[], int);
void AddName(User[], int&);
void ListAllUsers(const User[], int&);
void Prefix(User, int);
void ChangePhone(User[], int&);
void Help();
void DeleteUser(User[], int&);
bool Search(string x)
{
return (phone.find(x) != string::npos);
}
};
user.cpp
#include "User.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#pragma warning(disable:4996)
using namespace std;
const string PHONEBOOK_FILENAME = "phonebook.txt";
void User::Help()
{cout<<"\nWELCOME TO THE APPLICATION!\n";
cout<<"Press 0 to display on the screen all records that are saved in the file(phonebook.txt)\n";
cout<<"Press 1 to add 1 or more new record(s) in file(phonebook.txt)\n";
cout<<"Press 2 to delete permanently a record from file(phonebook.txt)\n";
cout<<"Press 3 to sort users from file(phonebook.txt) by name and display them on the screen\n";
cout<<"Press 4 to edit a user phone number and save it after in file(phonebook.txt)\n";
cout<<"Press 5 for help\n";
cout<<"Press 6 to exit the application\n";
}
void User::ReadAllUsers(User people[], int &num_people)
{
ifstream f;
f.open(PHONEBOOK_FILENAME.c_str());
if (f.fail())
{
cout << "Unable to open file " << endl;
return ;
}
int i = 0;
while (!f.eof() && i < 100)
{ getline(f, people[i].firstname);
getline(f, people[i].lastname);
getline(f, people[i].phone);
getline(f, people[i].country);
getline(f, people[i].city);
getline(f, people[i].street);
i++;
}
num_people = i;
f.close();
}
//Add country prefix to the phone number
void User::Prefix(User person, int num_people)
{string filecountry;
ifstream f;
f.open("prefix.txt");
{
while (getline(f, filecountry))
{
if (person.country == filecountry )
{
f.ignore();//next line
f >> person.prefix;
}
}
f.close();
}
}
void User::SaveUser(User person, int &num_people)
{
ofstream f(PHONEBOOK_FILENAME.c_str(), ios::app ) ;
if (f.fail())
cout << "Unable to open file " << endl;
else
f << person.firstname << " " << person.lastname << " " << person.country << " " << person.city << " " << person.street << " " << person.prefix << "-" << person.phone << endl;
cout << "\nThe user was added\n";
}
//Save data after a modification or after a user delete
void User::SaveToFile(const User people[], int num_people)
{ofstream f;
f.open(PHONEBOOK_FILENAME.c_str());
for(int i = 0; i < num_people; i++)
{
f << people[i].firstname << " " << people[i].lastname << " " << people[i].country << " " << people[i].city << " " << people[i].street << " " << people[i].prefix << " " << people[i].phone << endl;
}
}
// Read user data from the keyboard, add a new contact to the array
void User::AddName(User people[],int &num_people)
{User person;
cout <<"Enter the user's first name: ";
cin >> person.firstname;
cout <<"Enter the user's last name: ";
cin >> person.lastname;
cout <<"Enter the user's country: ";
cin >> person.country;
cout <<"Enter the user's city: ";
cin >> person.city;
cout <<"Enter the user's street: ";
cin >> person.street;
cout <<"Enter the user's phone number: ";
cin >> person.phone;
Prefix(person, num_people);
cout <<"The prefix is " << person.prefix;
for(int i = 0; i < num_people; i++)
{
if( i + 1 == num_people)
people[num_people] = person;
}
SaveUser(person, num_people);
num_people++;
}
// Ask the for person's name to change, find the person in the array and
// change it to the new phone number. Then save the new data to file by
// calling SaveToFile.
void User::ChangePhone(User people[], int &num_people)
{
User person;
int count;
cout <<"Enter name to change: ";
cin >> person.firstname;
for(count = 0; count < num_people; count++)
{
if(people[count].Search(person.firstname))
{ cout <<endl<< people[count].firstname<<endl;
cout <<"Current number"<<people[count].phone;
cout << "\nNew number: ";
cin >> people[count].phone;
SaveToFile(people,num_people);
cout <<"\n\nNew number Saved.";
return;
}
}
if(count = num_people)
cout <<"\nName not found.\n";
}
void User::DeleteUser(User people[], int &num_people)
{string phone;
int count = 0;
ifstream f;
f.open("phonebook.txt");
cout << "Input the phone of user that you want to delete ";
cin >> phone;
for(count = 0; count < num_people; count++)
{
if(people[count].Search(phone))
{ cout <<endl<< people[count].phone<<endl;
people[count].firstname = people[count].lastname = people[count].phone = people[count].country = people[count].city = people[count].street = " ";
}
SaveToFile(people,num_people);
cout <<"\n\nUser deleted.";
return;}
f.close();
}
The function Prefix()(this is to add automatically a country prefix for phone number, this is read from a file) is working but the value of person.prefix it's not taken by SaveUser(), so the value is not wrote in file.The function SaveToFile() save all users on single line in file.
And functions ChangePhone() and DeleteUser don't working.
The problem is that void User::Prefix(User person, int num_people) takes person by value, so it makes a copy of the person, changes the copy, then the copy goes away when the function ends. The original was never changed.
Instead, you want:
void User::Prefix(User & person, int num_people)
To have a reference to the person specified, which will be affected by the changes you make inside the function.
Also, I recommend you change your saveuser to be:
void User::SaveUser(User const & person, int &num_people) const
just to avoid making extra copies of the User object, but it's not incorrect the way you currently have it, I don't think.

Bookshelf Data Structures Issues

I am making a bookshelf of width size s(1<s<100). Add book id and the book width at the leftmost of the vector. If you add a book which causes the width to be exceeded, then delete the rightmost book until the book to be added can be put on the shelf. In the end, the remaining books on the bookshelf can be added.
The issue I am facing that when var = 'E' the program should display the remaining books on the shelf and then exit that problem and go to a different problem, but when 'E' is entered the remaining books on the shelf will not display, and the program will not exit. I have tried messing with the while loops condition that is nested in the overall while loop.
#include <iostream>
#include <vector>
using namespace std;
struct book{
int id;
int w;
};
int main(){
//std::vector::~vector
//create instance of book
book my_book;
//initialize the placeholders
int s, removed_book, back_width;
char var;
//create the vector
vector<book>shelf;
while(true){
//enter the s value
s = 0;
cout << "enter the s value: " << endl;
cin >> s;
int w_total = 0;
//be able to exit the program
if(s == -1){
return 0;
}
int x = 1;
//while remaining space
while(x!=0){ //need to fix this up
cout << "enter the action(A,R,E): " << endl;
cin >> var >> my_book.id >> my_book.w;
//if A
if(var == 'A'){
//get info about the book
/*
cout << "enter id: " << endl;
cin >> my_book.id;
cout << "width(w): " << endl;
cin >> my_book.w;
*/
w_total += my_book.w;
shelf.insert(shelf.begin(),my_book);
cout << "total width(1): " << w_total << endl;
if(w_total > s){
while(w_total >= s){
//remove the rightmost(back) book
w_total = w_total - shelf.back().w;
cout << "total width(2): " << w_total << endl;
shelf.erase(shelf.end()-1);
}
}
}
//if R
else if(var == 'R'){
//cout << "which book to be removed? : " << endl;
//cin >> removed_book;
removed_book = my_book.id;
for(int i = 0; i < s; i++){
if(shelf[i].id == removed_book){
shelf.erase(shelf.begin()+i);
}
}
}
//if E
else if(var == 'E'){
cout << "remaining books on shelf: " << endl;
for(int i = 0; i < shelf.size(); i++){
if(shelf[i].id!=0){
cout << "id: "<<shelf[i].id << endl;
}
}
//maybe put the display in here?
x = 1;
}
}
//print out the remaining shelf
shelf.clear();
//erase the shelfs(vectors) contents
//increase problem number
}
return 0;
}
Expected output:
10(shelf width)
A 1 3(Add id width)
A 2 5
E
-->PROBLEM 1: 2 1
cin >> var >> my_book.id >> my_book.w is asking the user to enter three things: a character and two integers. You have to enter all three before the action in var will be checked and acted upon.

What is a deleted function, and why only my functions that I pass files into are considered deleted? [duplicate]

This question already has answers here:
Using fstream Object as a Function Parameter
(3 answers)
Closed 6 years ago.
#include <bits/stdc++.h>
using namespace std;
class contact {
private:
vector< pair<string, int> > contact_info;
public:
void add_contact(string contact_name, int contact_number) {
contact_info.push_back(make_pair(contact_name, contact_number));
sort(contact_info.begin(),contact_info.end());
}
void edit_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
cout << "Enter the new number: ";
cin >> contact_info[found_at].second;
}
void show_all() {
for (unsigned int i =0; i < contact_info.size(); i++) {
cout << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void delete_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
contact_info.erase(contact_info.begin()+found_at);
}
void writeFile(ofstream contact_file) {
for (unsigned int i =0; i < contact_info.size(); i++) {
contact_file << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void readFile(ifstream contact_file) {
string input;
while (!contact_file.eof()) {
contact_file >> input;
size_t pos = input.find(" ");
string name = input.substr(0,pos);
string number_str = input.substr(pos);
int number = stoi(number_str) ;
contact_info.push_back(make_pair(name,number));
}
}
};
int main()
{
int choice;
ifstream contacts_file_read;
contacts_file_read.open("contacts.txt");
ofstream contacts_file_write;
contacts_file_write.open("contacts.txt");
bool in_prog = true;
contact contacts;
string name;
int number;
while (in_prog) {
cout << "1. Add contacts" << endl
<< "2. Edit contact" << endl
<< "3. Delete contact" << endl
<< "4. Show all" << endl
<< "5. exit" << endl;
cout << "Your choice: ";
cin >> choice;
contacts.readFile(contacts_file_read);
if (choice == 1) {
cout << "Enter name & number separated by a space: ";
cin >> name >> number;
contacts.add_contact(name, number);
} else if (choice == 2) {
cout << "Enter name of contacts to be edited: ";
cin >> name;
contacts.edit_contact(name);
} else if (choice == 3) {
cout << "Enter name of contact to be deleted: ";
cin >> name;
contacts.delete_contact(name);
} else if (choice == 4) {
contacts.show_all();
} else if(choice == 5) {
contacts.writeFile(contacts_file_write);
} else {
cout << "Wrong choice" << endl;
}
}
return 0;
}
So, I was asked in my programming class to make a phone book application in C++ using only objects, so this is my attempt at it.
All functions are good, I did recompile the program after finishing each function at it gave me 0 errors, however whenever I try to call writeFile or readFile function that were previously working fine, now the compiler gave me an error of "error: use of deleted functions... "
I don't know what are deleted functions and why only functions that take file objects as an argument are treated as such.
Can anyone please help?
Thanks.
Objects of type std::ifstream are not copyable -- indeed, the object represents the unique handle of an open file, and it would be difficult to conceptualize what it would mean to copy such unique responsibility.
Indeed, this inability to copy an object is encoded by making the copy constructor deleted, which causes the error that you see when you do attempt to copy it.
Your code should pass the original ifstream, not a copy (by taking a reference parameter):
void readFile(ifstream & contact_file)
// ^^^^^^^^^^