I'm doing some testing on an idea that I have. However, I am at loss.
I have declared a class as such :
class Course {
private:
char *name;
int ID;
public:
void printCourses();
}
Where printCourses() is defined as
void Course::printCourses() {
cout << name;
}
This makes sense. Each class has a data member called name. So, say that I have declared an array of 10 class objects, that means 10 potential names will correspond with to a course...OK.
My problem lies here.
What if object 6 and 9 have those values filled at some point during runtime, and I want to KNOW that. For instance, say course 6's name is "Psychology" and course 9's name is "History". I want to be able to print these values in a sort of "Course List" function... Some class objects are not yet filled here but I want to be able to parse through and find the objects that do have the name variable filled.
I have tried a for loop for testing this but no logic is helping... I tried this.
for (int i=0; i<10; i++) {
course[i]->printCourses();
}
In my head, this should still iterate through all 10 objects (I have already allocated memory for all 10 of them), but it doesnt. However, if I just call the one I know is filled like this:
course[6]->printCourses();
It returns properly "Psychology".
TLDR: Help, How can I iterate through class objects to find certain variables that are filled ?
disclaimer
I am using -> operators for classes because I declared the array as an array of pointers to the class objects.
Course *course[10];
Like so..
Before I answer, a side note. You say: "I have already allocated memory for all 10 of them." This is bad. You've wasted space on names that will never be used. Instead let's use a string to allocate as necessary, and to allocate any number of characters as desired.
Now, you need to use optional to solve this. Specifically your name shouldn't be definied as char* name but a optional<string> name. To use optional you'll just need to change your printCourses method:
void Course::printCourses() const { cout << name.value_or(""); }
Live Example
You could make a additional method that returns your name. If the name is a nullptr, you ignore it. Your method could look like:
char* Course::GetName()
{
return name;
}
And then you iterate with:
for (int i = 0; i < 10; i++) {
if (course[i]->GetName())
course[i]->printCourses();
}
An alternative way is to combine the functions:
void Course::printCourses() {
if (name)
std::cout << name;
}
Iterate with the following and it will only print the name if it exist:
for (int i = 0; i < 10; i++) {
course[i]->printCourses();
}
It would be good to initialize the name in the constructor:
Course::Course() : name(nullptr), ID (0) {}
Little side note: Use std::string instead of char*. I provided you a solution for your case but you can do pretty much the same with a solid c++ string.
Related
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 4 years ago.
Improve this question
For my assignment I have to make a program to read student data from standard input, sort it by last name / first name, and print out the result to standard output. Students consists of a last name, first name, and a grade point average. It says to there are no more than 50 students.
It also says you should not rely on an external library function to do the sort.
Here is the example:
Ware Henry 87.2
Dantes Edmond 91.4
Earhart Amelia 92.6
Here is how it should be sorted:
Dantes Edmond 91.4
Earhart Amelia 92.6
Ware Henry 87.2
Here is the code I have so far that is not working properly:
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
student();
void input();
void output();
void sort();
private:
string Fname;
string Lname;
float gpa;
}
student::student()
{
Fname = "";
Lname = "";
gpa = 0;
}
void student::input()
{
cout << "Enter first name, last name, and gpa"<<endl;
cin >> Fname >> Lname >> gpa;
}
void student::sort()
{
char temp;
int count = 0;
int i = 1;
while (i < word.size()) {
if (word[i - 1] > word[i]) {
temp = word[i];
word[i] = word[i + 1];
word[i + 1] = temp;
i++;
if (i >= word.size())
{
alpha(word);
}
}
else
{
count++;
}
}
return word;
}
void main()
{
student.input();
}
Any advice on where I went wrong and any possible solutions?
your student class has member variables to hold only one student, you need 50 instances of class student.
then you should hold these instances in an array/vector (whatever for container you are allowed to use) I assume you need to use a raw array so something like this will do.
student* students = new student[50];
what you then need is a compare function in your class to be able to sort the array, the compare function knows the internals of your class and you can decide how you want to sort the list e.g. after surname.
the sort function could be inside your class declared as a static function or maybe more logically an external function since student is not a container of student instances.
don't forget to delete the array when done
delete [] students;
in real world problems you would use std containers and e.g. algorithm sort for this kind of work.
Your compiler must have told you that word and alpha used in sort method are undeclared identifiers and count is assigned but never used.
Solution: Never ever steal code from wild wild web without understanding what it does. You may take others' code as inspiration, but blind copy-paste is a big no-no.
To give you a next step: you haven't even stored your students, you just input one, how would you sort just one entry? Think (and code) what you should use to store them and start working from there on how to sort them.
Good luck.
There are several reasons why your code is not working, first reason is that your class definition needs semicolon ';' at the end to close it.
class student
{
public:
student();
void input();
void output();
void sort();
private:
string Fname;
string Lname;
float gpa;
}; //semicolon here
In your sort() method the variable word is used but never declared, coding is not magic, the variable must declared and initialized before it is used like in your code.
while (i < word.size()) { //word must be declared somewhere
Also, in the sort method, you call a function alpha(word), this function does not exist in your program.
The sort method is of type void, which means it will not return anything, yet you are trying to return a string.
Another problem with the sort method is that it is never called from anywhere and will never be run.
There is also a big problem here with the way you are trying to use your class. To use the methods of the class you first have to instantiate an object of that class, you can then access the methods of the class through the object like this:
int main()
{
student theStudent;
theStudent;
theStudent.input();
return 0;
}
Another fundamental problem is that you are only going to get data for one object like this, you need to store several objects in something like an array and then sort the objects in the array:
int main()
{
student students[5];
for (int i = 0; i < 5; i++)
{
student newStudent;
students[i] = newStudent;
newStudent.input();
}
sort(students);
delete[] students;
return 0;
}
Which brings us to the sort method. It would be wise to not do the sorting as a method of the student class, but as a function called from main instead (like in the example above), that way it is easy to sort the array of student objects from main.
These are a few advice to start with, i am not going to do your complete homework for you though, if you use google and some of your precious energy, i believe that you will succeed.
This question does look like a copy and paste of an old one (which it sort of is) but I assure you the situation is a lot more different and very hard to explain so please hear me out before you murder my miniscule reputation.
I am having issues with taking vectors holding objects into function parameters, then scanning them and putting a specific object into another function's parameters which would then use all the values of that specific object.
For instance if there were a player class and enemy class:
class player{
public:
int id;
string name;
};
class enemy{
public:
int eid;
string name;
};
And there were some objects of those classes stored in their own vectors:
player example;
example.id = 1;
example.name = "example";
enemy badEnemy;
badEnemy.eid = 1;
badEnemy.name = "badEnemy";
vector<player> allPlayers;
vector<enemy> allEnemys; //I know the spellings wrong but am to reluctant to change it
allPlayers.push_back(example);
allEnemys.push_back(badEnemy);
And then there was a function that printed out the objects names:
int fightEnemy(player player, enemy enemy) {
cout << player.name << endl;
cout << enemy.name << endl;
return 0;
}
After that there would be a function that scans for specific objects in the vector and inserts them into the fightEnemy function
int enemyComboCheck(int id1, int id2, vector<Player>* allPlayers, vector<enemy>* allEnemys){
int iteratorForPlayer = 0;
id1 -= 1;
id2 -= 1;
for(int i = 0; i < 18; ++i){
if(id1 == allPayers[iteratorForPlayer].id && id2 == allEnemys[i].id) fightEnemy(allPlayers[iteratorForPlayer], allEnemys[i]);
//how do I pass the scanned object into the other function
}
return 0;
}
I guess my main question is how do I pass the scanned object into the other function through a vector? Would I have to use a vector in the other function?
Sorry for all the bad formatting, anyways thanks!
You pass it exactly the same way you're referencing them in your if statement.
fightEnemy(allPlayers[iteratorForPlayer], allEnemies[i]);
And fix the spelling. That's what global find and replace is for.
I would suggest changing the signature of fightEnemy to take references so you don't have to copy objects, and you can change things like hitpoints if you need to. This will not change the way you call it:
int fightEnemy(player &player, enemy &enemy)
I'm quite new to C++. I've been trying to figure this out for days - there'll be an easy solution no doubt but I haven't been able to find it (after much googling)! My problem is this:
I'm trying to create a class with a member function that reads in characters from a file and stores them in an array. I want to be able to create multiple objects (not sure how many - decided by the user), each with their own arrays filled with characters taken from different files. I think I've managed to do that. How would I then go about accessing the object's array in main?
The code I'm working on is long and messy but something along these lines (char.txt contains simply '12345' in this case):
#include <iostream>
#include <fstream>
using namespace std;
class Something{
public:
void fill_array(char array_to_fill[]){
char next;
ifstream input;
input.open("chars.txt");
input.get(next);
while(!input.eof())
{
for(int i = 0; i < 6; i++)
{
array_to_fill[i] = next;
input.get(next);
}
}
}
};
int main()
{
Something* something = new Something[1];
char array_to_fill[5];
something->fill_array(array_to_fill);
//I'd like to be able to access the array here; for example - to cout the array.
return 0;
}
Apologies if a) my terminology is wrong b) my code is rubbish or c) my question is stupid/doesn't make sense. Also I should add I haven't learnt vectors yet and I'm not supposed to use them for the program I'm making. Any help would be much appreciated. Cheers!
Your class does not store the array at all. It is simply a holder for a method. You probably want something like this, where each instance of the class holds the array. (I changed it to std::string since they are nicer to work with.)
class Something
{
private:
std::string data;
public:
void fill_data( const std::string& filename )
{
ifstream file( filename );
file >> data;
file.close();
}
std::string get_data() const
{
return data;
}
}
int main()
{
std::vector<Something> my_things;
my_things.push_back( Something() );
my_things[0].fill_data( "chars.txt" );
cout << my_things[0].get_data() << std::endl;
my_things.push_back( Something() );
my_things[1].fill_data( "another_file.txt" );
cout << my_things[1].get_data() << std::endl;
}
Since you are using C++, not C, get used to writing C++ code instead of C. (std::vector instead of C arrays (for unknown length arrays), std::string instead of char*, etc).
I think your question is too general for the format of stack overflow, but what you want in this case is to either create a public member, or create a private member with setters and getters.
class Something
{
public:
std::string m_string;
}
int main()
{
Something A;
A.m_string = "toto";
cout << A.m_string;
return 0;
}
Put a string for convenience (you could use a const char* but you will have to understand what is the scope to know when it will not be accessible anymore and you are not quite there yet) and there may be typos since I typed this from a phone.
If you really want to access the chars themselves, pass a char* with a size_t for the length of the array or use std::array if possible.
Right now the method fill_array is creating a local copy of array_to_fill, so any changes that you make to array_to_fill only happen in the local method. To change this, pass by pointer. This way the pointer gets copied instead of the whole array object. I didn't test this but it should look more like this:
void fill_array(char* array_to_fill){
...
}
You don't need to change anything in the main method.
To actually access the elements you can use [] notation. I.e. cout << array_to_fill[0] in the main method.
Edit: I think that change should work.
I need a little bit of help with using pointers in C++. Sorry to seem beginner but I really can't quite understand them. I have read the tutorial on pointers on the cplusplus.com website, so please don't suggest that.
I basically have a variable which holds the name of another variable, and I wish to access that variable through the holder one. I believe I need to use pointers, correct me if I'm wrong though.
E.g.
int a;
string b;
a = 10;
b = "a";
I need to access the variable "a" through the contents of variable "b".
Just to put this into better perspective, this is how I am using it:
int a;
a = 20;
void getVar(string name) {
cout << name;
}
getVar("a");
But as you can see, on the fifth line, that will just cout the value of name, in this case "a", but I want it to cout the value of the variable which name contains, so I want it to output "20".
Any help here would be much appreciated.
If you need to associate a name with a value, consider associative arrays otherwise known as dictionaries and maps. The Standard Template Library has std::map that you can use to associate text with a value:
#include <map>
#include <string>
std::map<std::string, int> my_map;
my_map["A"] = 20;
cout << my_map["A"] << endl;
What you are thinking of is called (Reflection) which C++ does not support. You can however use pointers to access what is in a variable it points to:
int a = 5; //int variable that stores 5
int *b = &a; //int pointer that stores address of a
(*b) = 10; //stores 10 into address that b points to (a)
cout << a; //prints 10
What you are trying to achieve is not possible in a compiled language (not considering reflection). You might accomplish something similar using a map data structure.
theMap["a"] = 20;
and a corresponding
void getVar(string key){
cout << theMap[key];
}
that can be called with
getVar("a");
Note that in this extremely simple sample theMap has to be in scope for the function, like in a class or a namespace.
If you use pointers you are just using a level of indirection not at all suited for your example. See Chads answer for instance.
Theres no real way for you to access variables by name like that unless you create some kind of container class that has a name member that you look up by. I'm not sure what this has to do with pointers though.
What you're asking for is called "reflection" or "introspection" - the ability to use design-time names for your program's objects (classes, variables, functions, etc) in run time. C++ does not support that out of the box - the design-time names are stripped upon compilation.
There are some libraries that provide that capability in C++; but there are also languages where reflection is is part of the language. Python or JavaScript, for example.
Maybe this could suit you:
int a = 5;
class b {
public:
b(int &x) { ref_ = x; }
int operator()(void) { return ref_; }
private:
int &ref_;
}
b my_b(a);
my_b() /* -> 5 */;
Your code does not use pointers. you're trying to convert a string into an identifier and print it's result, I don't know whether that's possible or not. If you intended using pointer your code should've looked like this:
int a = 20;
int* b = &a;
cout << *b;
quick fix for outputting integers only:
int a;
a = 20;
void getVar(int name) {
cout << name;
}
getVar(a);
If you need the function to work for any type of variable, maybe think about some template function.
Edit: Here is the code for the template program:
#include <iostream>
#include <string>
using namespace std;
template <class T>
void getVar(T name){
cout<<name<<endl;
}
int main()
{
string x="hee";
int y=10;
getVar(x);//outputs hee
getVar(y);//outputs 10
return 0;
}
My task was as follows :
Create class Person with char*name and int age. Implement contructor using dynamic allocation of memory for variables, destructor, function init and friend function show. Then transform this class to header and cpp file and implement in other program. Ok so here's my Person class :
#include <iostream>
using namespace std;
class Person {
char* name;
int age;
public:
Person(){
int size=0;
cout << "Give length of char*" << endl;
cin >> size;
name = new char[size];
age = 0;
}
Person::~Person(){
cout << "Destroying resources" << endl;
delete [] name;
delete take_age();
}
friend void show(Person &p);
int* take_age(){
return &age;
}
char* take_name(){
return name;
}
void init(char* n, int a) {
name = n;
age = a;
}
};
void show(Person *p){
cout << "Name: " << p->take_name() << "," << "age: " << p->take_age() << endl;
}
int main(void) {
Person *p = new Person;
p->init("Mary", 25);
show(p);
system("PAUSE");
return 0;
}
And now with header/implementation part :
- do I need to introduce constructor in header/implementation files ? If yes - how?
- my show() function is a friendly function. Should I take it into account somehow ?
I already failed to return this task on my exam, but still I'd like to know how to implement it.
Solve many of your issues, by switching from char * to std::string. You'll be glad you did.
The std::string class takes care of memory allocation, and deallocation as well as copying.
If this is homework, convince your professor to use std::string for beginners and save char * for the section on pointers. Also remind your professor that the C++ langauge is different than the C language. This is one of those areas.
You don't need a * when using delete or delete[]. Just supply a pointer variable to it eg.
delete[] name;
Also, your take_age member claims to return a int* but you actually return the int member itself. You need to take the address of the member using & if you want to do that. As #Jerry has commented this is not what you want to do here.
Although some on this site apparently think it is completely acceptable, good practice (see Can a constructor return a NULL value?), you should really refrain from doing things like stream operations within the constructor of your object. Do that stream reading outside and then call the function with the results.
That is, IMHO, the first step you should take.
In a typical case, managing a pointer and block of dynamically allocated memory (such as the name in this case) is enough responsibility for one class. As such, Thomas Matthews is right: you should really use string in this case. If you're going to handle it yourself, you should still split that responsibility off into a class of its own, and embed an object of that class into your Person object. If anything, std::string already tries to do too much; you'd be better off with something that does less, not more.
Your deletes should exact match with your allocations. In this case, the only allocation is:
name = new char[size];
so the only deletion should be:
delete [] name;
As far as friend functions go, you normally want the friend declaration inside the class definition, but the function definition outside the class definition:
class Person {
// ...
friend void show(Person const &);
// ...
};
void show(Person const &p) {
// ...
}
There are other possibilities, but that's the general idea. In particular, a friend is never a member function. What you had was a declaration of one (global) function named show and a definition of a completely separate member function -- that happened to have the same name, but wasn't really the same function at all.
That shows one other point: const-correctness. You were passing the parameter as a reference to Person. Unless it's going to modify the Person object (in which case, show() seems like a poor choice of name), it should probably take a reference to a const object. The same general idea applies to take_age() -- since it only retrieves a value, it should be a const function:
int take_age() const { return age; }
I've probably already tried to cover too much, so I'll shut up for the moment...
I think you should investigate the following pieces of your code (like, what's beneath them, what happens here, etc...)
int * take_age(); // You should return plain `int` here, I assume
~Person(){
cout << "Destroying resources" << endl;
delete *[] name; // Do you understand why did you put `*` here?
delete * take_age(); // Do you understand why did you write this? What behaviour you were trying to achieve?
And, actually, so on. Only when you're done with the basic stuff, I think, you can move on to header designing questions and friend functions.
First off, kudos on trying to find the right way to implement your class, particularly after having missed the answer already.
From your description at the top, I think you may have misunderstood some of what was being asked for this assignment. First, my interpretation would be that setting the value of the name and age should take place in the init() function rather than in the constructor. As mentioned by several other posters, your constructor should simply initialize your class to a known-good state. For example,
Person() {
name = NULL;
age = 0;
}
Then in your initialization function, you can assign the values. Looking at your original init() function, it should probably be mentioned that simply assigning a pointer value (char *) to another pointer (char *) only copies the value of the pointer, not the data that it represents. Thus, for the assignment of the name value you need to calculate the size of the buffer you need, allocate the buffer, and copy the data yourself. A basic init() function would probably look like
init(const char *n, int a) {
// Calculate the required name length plus a NULL-terminator
size_t nameLen = strlen(n) + 1;
// Free any previous value.
if (name != NULL) {
delete[] name;
}
// Allocate the name buffer and copy the name into it.
name = new char[nameLen];
memcpy(name, n, nameLen);
// Store the age.
age = a;
}
Finally, in your destructor you free any resources allocated by your class, in this case the name buffer.
~Person() {
if (name != NULL) {
delete[] name;
}
}
If you have a book or something associated with your class, you may want to review the information on pointers. They can be a bit tricky but are important to learn. I suspect that is why the problem specified using char * for strings rather than the STL string class.
To your question about placing information in header and source files, it is often considered good practice to create a header file that contains the class declaration and member function prototypes and then provide the implementation of your methods in a separate source file. For some simple functions, you can provide an implementation directly in your header file.
The key when providing class member definitions in a separate source file is to provide the class name to properly scope the function (i.e., Person::). So your header file may contain a class definition like
// Header file (e.g., person.h)
class Person {
private:
char *name;
int age;
public:
Person() { name = NULL; age = 0 };
~Person() { if (name != NULL) delete[] name; }
void init(const char *n, int a);
// Other method declarations and/or definitions
};
And then in your source file
// Source file (e.g., person.cpp)
void Person::init(const char *n, int a) {
// ...
}
// Rest of method definitions
Source files that use your person class need only include the header file with your class definition.
I think your problem is with this line:
friend void(Person &p);
What is it needed for.
do I need to introduce constructor in header/implementation files ?
The constructor can be in the .h or the .cpp file. It doesn't matter. Generally if the function is short it is ok to include it in the .h file. Anything longer should go in the .cpp.
my show() function is a friendly function.
Not sure what you mean by this. friend functions exist outside the class definition. Your show function is defined inside the class so does not need to be a friend.
in addition to the previously posted answers, i've got two points of advice for you:
don't use 'friend'. some here may disagree with me, but 'friend' should really not be part of C++ anymore as it goes against what OOP stands for.
naming your methods: avoid naming your methods like 'take_name' or 'take_age'. conventionally, since those are getters, consider naming them 'getName' and 'getAge'. you end up with much more respect from developers this way.