I'm working on a C++ assignment and having some issues with an error in regards to push_back. The error message reads:
No matching member function for call to 'push_back'.
The error occurs at the line that reads: book.push_back(name,number,email);
Here is the code:
//Program
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
// Declaring ye ol' phonebook structure //
struct phoneBook {
public:
string name;
int number;
string email;
};
int main(){
// Declaring the VECTOR of the Phonebook
vector<phoneBook>book;
string fileName;
//reading the file
cout <<"Enter file name to read contacts: ";
cin >> fileName;
std::string myline;
std::ifstream infile(fileName);
while (std::getline(infile, myline))
{
std::istringstream iss(myline);
string name;
int number;
string email;
if(!(iss >> name >> number >> email)) {break;}
//pushing into vector
book.push_back(name,number,email);
}
//reading extra contacts from user
while(true){
int choice;
cout << "Do you want to add extra contact? If so, type 1. If not, type 2 to exit:";
cin >> choice;
if(choice == 1){
string name;
int number;
string email;
cout << "Enter name: ";
cin >> name;
cout << "Enter number: ";
cin >> number;
cout << "Enter email: ";
cin >> email;
book.push_back(name,number,email);
}
else{
break;
}
}
//printing phone book
cout << "Contacts are here: " << endl;
for(int i=0;i<book.size();i++){
cout << book[i].name << ""<<book[i].number<< "" << book[i].email << endl;
}
return 0;
}
Note that std::vector::push_back expects only one argument with type of the element of the vector
, i.e. a phoneBook
.
If you want the element (to be added) constructed from the arguments directly you can use emplace_back (since C++11) instead, e.g.
book.emplace_back(name,number,email);
or you can change it to use braced initializer (also since C++11):
book.push_back( {name, number, email} );
For pre-C++11 you can change it to construct a phoneBook
explicitly.
book.push_back( phoneBook(name, number, email) );