Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
void Add(vector< vector<string> > &name,
vector< vector<string> > &author,
vector< vector<string> > &pub,
int &total_books)
{
Line();
string book_name,book_author,book_pub;
cout << "Please enter the book name: ";
cin >> book_name;
cout << "Please enter the author name: ";
cin >> book_author;
cout << "Please enter the publisher name: ";
cin >> book_pub;
name.push_back(book_name);
author.push_back(book_author);
pub.push_back(book_pub);
++total_books;
cout << "The book has been successfully added.";
}
Compiler says this:
[Error] no matching function for call to
'std::vector<std::vector<std::basic_string<char> >>::push_back(std::string&)'**
Does anybody know what's the problem?
With a std::vector<std::vector<string> >, you need to push_back an instance of std::vector<string>.
Example:
std::vector<string> many_strings;
std::vector<std::vector<string> > matrix_of_strings;
many_strings.push_back("Sid");
many_strings.push_back("Alice");
many_strings.push_back("Bob");
matrix_of_strings.push_back(many_strings);
In your case, a better solution is to make a structure with the fields rather than using parallel vectors.
struct Book
{
std::string title;
std::string author;
std::string publisher;
};
You can then add an input function:
struct Book
{
//...
void input_from_user();
};
void Book::input_from_user()
{
std::cout << "Enter book title: ";
std::getline(title);
std::cout << "Enter book author: ";
std::getline(author);
std::cout << "Enter book publisher: ";
std::getinle(publisher);
}
Your input process could look like this:
Book b;
b.input_from_user();
Your database would look like this:
std::vector<Book> database;
database.push_back(b);
Your variables are vectors of vectors (vector<vector<string> > &name), which seems to be one level to deep - you cannot push_back a string into those, but only a vector of strings.
What are you trying to accomplish with this? Why not simply use vector<string> &name, which should work just fine?
Sure, you're trying to push a string into a vector of vectors.
First, why are those vectors two-storeyed? If you change them into vector<string> no other changes will be needed (in this fragment.)
void Add(vector<string> &name, vector<string> &author, vector<string> &pub);
Next, if, due to some reason you still need them to be double level, well, you can insert fresh strings as singletons:
name.push_back({book_name});
(may need more verbosity in older standard:
author.push_back(vector<string>(1, book_author));
or add them to vector's most recent element:
pub.back().push_back(book_pub);
Perhaps, in the latter case you first need to check if the large vector is not empty, so there's a back().
It is unclear from your snippet what you're trying to achieve.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've been told to read/write disc as little as possible. For this solution, I've made a constructor that reads the file on object construction and fills the unordered map with the contents of the file. Is this a good way/practice to read from .txt files?
In terms of printing out the contents of the file, I've mentioned readFile again. Is this ok to do? I couldn't really find another way without making it global. Here is the code below:
class Test {
private:
string name;
string number;
unordered_map<string, string> mappy;
public:
Test()
{
ifstream readFile("A:\\Coding\\namesNumbers.txt");
while (readFile >> name >> number)
{
mappy[name] = number;
}
}
void print()
{
ifstream readFile("A:\\Coding\\namesNumbers.txt");
while (readFile >> name >> number)
{
for (int i = 0; i < 1; i++)
{
cout << name << ":" << " ";
cout << number << endl;
}
}
}
~Test() {};
};
You are reading the file twice. When you don't mind the order of the items, then you can also print from 'mappy'.
Note that it is better to declare 'name' and 'number' as local as possible.
(Consider using another data type for 'number' i.s.o. 'string'.)
In the code below, I assume you have C++17 (for Structured binding)
class Test {
private:
unordered_map<string, string> mappy;
public:
Test()
{
ifstream readFile("A:\\Coding\\namesNumbers.txt");
string name;
string number;
while (readFile >> name >> number)
{
mappy[name] = number;
}
}
void print()
{
for (auto [name, number] : mappy)
{
cout << name << ":" << " ";
cout << number << endl;
}
}
~Test() {};
};
Reading a file in a construct is not necessarily a bad practice. Depends on the intended usage of the class. Sometimes you need to separate (default) construction from the reading of the data. In such a case you can provide two constructors: one for default construction and one for construction with file reading. As long as your solution satisfies, you can stick to that.
string firstname, lastname;
string phonenumber, email;
cout << "What is the first of the person that you would like to add? : ";
cin >> firstname;
cout << "What is the last of the person that you would like to add? : ";
cin >> lastname;
cout << firstname << " " << lastname << endl;
cout << "What is the phone number of that person? : ";
cin >> phonenumber;
I need help taking this user input and plugging it into an array. I honestly do not know how to do that, if I could get some help on that it would be great!
Create a struct named Record as follows
struct Record
{
string firstName, lastName,phone; //etc
};
If you know how many records you want to enter then you have to create an array of Record as follows
Record PersonInfo[5];
Now each index of PersonInfo let say PersonInfo[2] is a complete Record and you can access there fields like
PersonInfo[2].phone = "5655567" //etc
Now if you want to create array of Record but don't know the size then your best bet for now is to use a vector like follows. A vector is an array of changable size. You need to include the following header
#include<vector>
After wards you can do the following
vector<Record> PersonInfo //thats how vectors are declared
The name between <> bractes tell of what type you want a vector of ,you can write int as well.
Following is how you add items to a vector
Record r1,r2; // just for example
PersonInfo.push_back(r1);
PersonInfo. push_back(r2);
you may add any number of items in it and you can access them just like array as follows
PersonInfo[0] .lastName // its actually r1.lastName and so on
This may seem difficult for now you may want to learn vectors and their operations before going for dynamic memory allocation which requires that you understand what pointers are. I don't know that you know about pointers and how to use them that is why I reffered you vectors
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is mine Full code. Am trying to Include inpatient if the case is one(1) but some highlight show that is wrong. is there anyhow to fix this if not can you please tell me another way to do it as long as it include inpatient if one(1) is Entered
void selection(int &);
void processor(int &);
void inPatient(double &, double &, double &, double &);
int main()
{
int selected, include;
double numberOfDays, dailyRate, chargesForHospital, hospitalMedicationCharge;
selection(selected);
validate(selected, selected);
processor(selected);
system("pause");
return(0);
}
void selection(int & selectedOption)
{
cout << "\nEnter Selection: ";
cin >> selectedOption;
}
void processor(int & selectedOption)
{
switch(selectedOption)
{
case 1:
inPatient(umberOfDays, dailyRate, chargesForHospital, hospitalMedicationCharge);
break;
case 2:
cout << "out-Pat" << endl;
break;
default :
cout << "Nothing Selected" << endl;
break;
}
}
void inPatient(double & numberOfDays, double & dailyRate, double & chargesForHospital, double & hospitalMedicationCharge)
{
cout << "The number of days spent in the hospital: ";
cin >> numberOfDays;
cout << "The daily rate: ";
cin >> dailyRate;
cout << "Charges for hospital services (lab tests, etc.): ";
cin >> chargesForHospital;
cout << "Hospital medication charges: ";
cin >> hospitalMedicationCharge;
}
There are a number of errors in the code that you posted, but I'll try to address your immediate problem. You're trying to call a function like this:
patric(int & gender, int & age)
but that's more like a function declaration. To actually call the function, you pass in arguments but omit the type, like this:
patric(someGender, someAge);
The int & in the declaration says that the parameters are references to values of type int, so the values you pass when you call patric should be of type int.
Also, you say that patric is overloaded. That means that there are several versions of the function, each with different parameter lists. So, maybe there's the one above as well as one that doesn't take any values -- maybe their declarations look like this, respectively:
void patric(int &gender, int &age);
void patric(void);
Given that, if you wanted to call the second version, you'd just call it:
patric();
(The void in the parameter list in the second version means that the function doesn't take any parameters. The void before the function name means that it doesn't return anything.)
Note also that you need a semicolon (;) following the function call.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been debugging this for a long time now - but I have no clue what the issue is.
I get a name from the console (via std::cin) and then proceed to create a new Player object with it. Then I pass the new object to the Gameboard to be added to a std::vector<J> where J is part of a template. Here's the code:
main.cpp
Gameboard<Tile,Player,5,5> board = Gameboard<Tile,Player,5,5>();
std::string name;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
std::cout << std::endl;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
std::cout << std::endl;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
gameboard.h
template<class T, class J, const int X, const int Y>
class Gameboard {
std::vector<J> players;
public:
void setPlayer(J player);
};
template<class T, class J, const int X, const int Y>
void Gameboard<T,J,X,Y>::setPlayer(J p) {
////// DEBUG CODE //////
std::cout << p.getName() << std::endl;
players.push_back(p);
for (int i = 0; i < players.size(); i++) {
std::cout << players.at(i).getName() << std::endl;
}
}
player.h/player.cpp
class Player {
std::string name;
public:
Player(std::string _name);
std::string getName();
};
Player::Player(std::string _name) {
name = _name;
}
std::string Player::getName() {
return name;
}
I think I've tracked my problem down to the code marked DEBUG CODE. Using the above code, and entering the names Bob, Joe, and Tim, I would get the following output:
Enter a name: bob
bob
Enter a name: joe
joe
Enter a name: tim
tim
[exit]
So somehow, when I add the player to the vector, it becomes corrupted or something similar. The object is valid right before insertion because I echo out the name. The vector is also growing in size because it's printing blank lines equal to the number of players added.
What is going on?
You might have a copy constructor where you are not copying the name. So when you push_back on the vector, a Player object with empty name gets pushed on the vector.
Implement the copy constructor properly and it should work
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I made a program that should take input print it. Then run a simple addition thing but when i use spaces in the input it skips through the addition. I do not know what the problem is.
this is the class stuff
#include <iostream>
#include <string>
using namespace std;
class Cheese {
private:
string name;
public:
void setName(string x){
cin >> x;
x = name;
}
string getName(){
return name;
}
void print(){
cout << name << endl;
}
};
this is the main stuff
int main()
{
string h;
Cheese hole;
hole.setName(h);
hole.getName();
hole.print();
this part is getting skipped through without letting me input
int x = 5;
int y = 16;
cout << x+y;
num(x);
int a;
int b;
int c;
cout << "Type in a number and press enter.";
cin >> a;
cout << "Repeat.";
cin >> b;
c = a+b;
cout << c << endl;
if(c <= 21){
cout << "Good job!";
}
else {
cout << "You fail!";
}
return 0;
}
I suggest you divide the responsibilities a little differently. The Cheese class's setName function should simply take a string and set the instance's member variable to the given argument.
Then your program can read from standard input and populate a string within main, and pass that string to setName.
To be more concrete:
class Cheese {
private:
string name;
public:
void setName(const string& x){
// change this code to set the 'name' member variable
}
[...]
};
And the main becomes:
int main()
{
string h;
Cheese hole;
std::string input_name;
cout << "Type a name and press enter.";
cin >> input_name; // Will read up to first whitespace character.
hole.setName(input_name);
hole.getName(); // this is a no-op: compiler may warn of unused return value
hole.print();
In general, reading standard input as part of a class's interface is a bad idea, because it makes it hard to re-use that class in the future (for example, with programs that take input from a file instead of from a human at a console).
The input that you pass to cin input stream skips any white space, Tab space or newline. If you wish to input string then you can use cin.getline(string s). The input after the white space gets passed to next waiting cin, as the next cin accepts integer and it get a character string it skips that. Thus when enter a string with white spaces the program skips the remaining part.