Make a String Variable a Class Name in C++ - c++

I'm working on a program in C++ to make schedules for me, since I have a hard time focusing on school work. The code will make priorities of assignments based on the due dates, duration to do the assignments, etc.
Anyway, I've run into a massive problem. I'm trying to assign a class variable's name to a variable! For example:
string a = "assignmentName" Class a(); //a is a variable and it's supposed to put the class's name as assignmentName
If you don't think this way will work, please tell me other solutions!
Also, I'm still a beginner, so please try to explain a little simple!
Here's the code:
#include <string>
#include <iostream>
using namespace std;
class Assignment
{
private:
int duration = 30; //Amount of time per assignment (in minutes)
int due = 1; //Amount of days till its due, if it's one then the assignment is due in 1 days
string name; //Name of assignment
public:
Assignment(int, int, string);
~Assignment();
void setDuration(int duration) {this -> duration = duration;}
void setDue(int due) {this -> due = due;}
void setDue(int name) {this -> name = name;}
int getDuration() { return duration; }
int getDue() { return due; }
string getName() { return name; }
};
Assignment::Assignment (int duration, int due, string name) //Constructor Method
{
this -> duration = duration;
this -> due = due;
this -> name = name;
}
Assignment::~Assignment() //Destructor Method
{
cout << "Assignment Object Destroyed" << endl;
}
int main()
{
int assignmentAmount;
int i;
int userInput1;
int userInput2;
string userInput3;
cout << "Enter assignment amount: ";
cin >> assignmentAmount << "\n" << endl;
for (i = 0; i < assignmentAmount; i++){
cout << "Enter assignment" << i <<"'s " << "duration: ";
cin >> userInput1 << endl;
cout << "Enter assignment" << i << "'s " << "due date in days from now: ";
cin >> userInput2 >> endl;
cout << "Enter assignment" << i <<"'s " << "name: ";
cin >> userInput3 >> endl;
Assignment i(userInput1, userInput2, userInput3); //I is the class's number and it's supposed to be a variable
}
return 0;
}

What you are looking for is an array of Assignment objects, eg:
int main()
{
Assignment *assignments;
int assignmentAmount;
int userInput1;
int userInput2;
string userInput3;
cout << "Enter assignment amount: ";
cin >> assignmentAmount << "\n" << endl;
assignments = new Assignment[assignmentAmount];
for (int i = 0; i < assignmentAmount; i++){
cout << "Enter assignment " << i << "'s duration: ";
cin >> userInput1 << endl;
cout << "Enter assignment " << i << "'s due date in days from now: ";
cin >> userInput2 >> endl;
cout << "Enter assignment " << i <<"'s name: ";
cin >> userInput3 >> endl;
// either:
assignments[i] = Assignment(userInput1, userInput2, userInput3);
// or:
assignments[i].setDuration(userInput1);
assignments[i].setDue(userInput2);
assignments[i].setName(userInput3);
}
// use assignments and assignmentAmount as needed...
delete[] assignments;
return 0;
}
Though, you should use std::vector instead of new[] directly:
#include <vector>
...
int main()
{
std::vector<Assignment> assignment;
int assignmentAmount;
int userInput1;
int userInput2;
string userInput3;
cout << "Enter assignment amount: ";
cin >> assignmentAmount << "\n" << endl;
for (int i = 0; i < assignmentAmount; i++){
cout << "Enter assignment " << i << "'s duration: ";
cin >> userInput1 << endl;
cout << "Enter assignment " << i << "'s due date in days from now: ";
cin >> userInput2 >> endl;
cout << "Enter assignment " << i << "'s name: ";
cin >> userInput3 >> endl;
// either:
assignments.push_back(Assignment(userInput1, userInput2, userInput3));
// or:
assignments.emplace_back(userInput1, userInput2, userInput3);
}
// use assignments as needed...
return 0;
}
Or:
#include <vector>
...
int main()
{
std::vector<Assignment> assignment;
int assignmentAmount;
int userInput1;
int userInput2;
string userInput3;
cout << "Enter assignment amount: ";
cin >> assignmentAmount << "\n" << endl;
assignments.resize(assignmentAmount);
for (int i = 0; i < assignmentAmount; i++){
cout << "Enter assignment " << i << "'s duration: ";
cin >> userInput1 << endl;
cout << "Enter assignment " << i << "'s due date in days from now: ";
cin >> userInput2 >> endl;
cout << "Enter assignment " << i << "'s name: ";
cin >> userInput3 >> endl;
// either:
assignments[i] = Assignment(userInput1, userInput2, userInput3);
// or:
assignments[i].setDuration(userInput1);
assignments[i].setDue(userInput2);
assignments[i].setName(userInput3);
}
// use assignments as needed...
return 0;
}

You can't get variable names as a variable, since a variable is basically like an alias to the data, when your program gets compiled all these names, don't exist anymore.

The compiler does not emit symbol names to the executable (the debug version may have symbol names).
If you want to associate or map symbol names to variables, you will need to declare the variable global and place the address into some kind of table.
Example:
int my_global_int_a;
std::map<std::string, int *> variable_dictionary;
variable_dictionary["my_global_int_a"] = &my_global_int_a;
// Here's how to get the variable
const std::string variable_name = "my_global_int_a";
int * p_variable = nullptr;
p_variable = variable_dictionary[variable_name];
std::cout << *p_variable << std::endl;
You may want to give deep thought to the need of retaining variable names.

Related

Input an amount of elements of a structure from keyboard (not having a constant value) c++

I need to input how many authors/rows there will be but with constant value it's impossible
In other words, this
const int n = 2;
struct books b[n];
int i;
must be changed to something like this
int n;
cin >> n;
struct books b[n];
I think the solution has something to do with dynamic allocation but I don't know exactly how to realize it
Full code:
#include <cstring>
#include <iostream>
using namespace std;
struct books
{
string name;
string nameOfBook;
string publisher;
int year;
};
int main() {
const int n = 2;
struct books b[n];
int i;
int n;
cin >> n;
struct books b[n];
for (i = 0; i < n; i++)
{
cout << "Author " << i + 1 << endl;
cout << "Enter name" << endl;
cin >> b[i].name;
cout << "Enter a name of a book" << endl;
cin >> b[i].nameOfBook;
cout << "Enter a publisher" << endl;
cin >> b[i].publisher;
cout << "Enter the year of publishing" << endl;
cin >> b[i].year;
cout << endl;
}
cout << "Author \t" << "Name of an author: \t" << "Name of a book: \t" << "Name of a publisher: \t" << "The year of publishing: \t" << endl;
for (i = 0; i < n; i++)
{
cout << i + 1 << "\t" << b[i].name << "\t\t\t" << b[i].nameOfBook << "\t\t\t" << b[i].publisher << "\t\t\t" << b[i].year << endl;
}
return 0;
}
What you want is an array that can be resized at runtime, which is known as a dynamic array. struct books b[n]; is a static array, meaning that it is resolved at compile time. So what you are looking for is std::vector<books> b(n).
Secondly you have some variables with the same name,
const int n = 2; // #1
struct books b[n]; // #2
int i;
int n; // <-- Redefinition of #1.
cin >> n;
struct books b[n]; // <-- Redefinition of #2.
You cannot have redefinitions in the same scope. So make sure that all your variables in a scope has different names.

Why won't Xcode (10.1) realize this class? What am I doing wrong

Basically trying to just run this program for extra learning, Xcode won't understand that I have written a class, and wont implement it. Really confused and need some guidance.
When I run the code only the main method is implemented, nothing else works...
#include <iostream>
using namespace std;
class students {
int id;
char name[20];
int s1;
int s2;
int s3;
public:
void getData() {
cout << "Enter the ID " << endl;
cin >> id;
cout << "Enter the name " << endl;
cin >> name;
cout << "Enter the grade in subject 1 " << endl;
cin >> s1;
cout << "Enter the grade in subject 2 " << endl;
cin >> s2;
cout << "Enter the grade in subject 3 " << endl;
cin >> s3;
}
void putData() {
cout << id << " " << name << " " << s1 << " " << s2 << " " << s3 << endl;
}
};
int main () {
students s[20];
int i, n; //i is for the for loop, n for number of students
cout << "Enter the number of students " << endl;
cin >> n;
for (i=0;i>n;i++)
{
s[i].getData();
}
for (i=0;i>n;i++)
{
s[i].putData();
}
return 0;
}

C++ Using Struct for employee record/Gross pay calculator

sorry I am relatively new to c++ and am currently stuck. The point of the application is to have the user enter the number of employees they have and then information about their employees including the hours they worked and their pay rate. After that that application to print out all the information and then give them each employees gross pay. I thought I had everything set up correctly but am getting an error on line 26 it is saying "expression must have constant value". Any tips or advice would be appreciated.
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>
#include<iomanip>
using namespace std;
struct Employee
{
int id;
string fName;
string lName;
int pay;
int hours;
};
int main() {
int i, n;
cout << "Enter number of employees";
cin >> n;
Employee Emp[n];
for (i = 0; i < n; i++) {
cout << "Enter Employee ID: ";
cin >> Emp[i].id;
cout << "Enter First Name: ";
cin >> Emp[i].fName;
cout << "Enter Last Name: ";
cin >> Emp[i].lName;
cout << "Enter in Pay Rate: ";
cin >> Emp[i].pay;
cout << "Enter in Hours: ";
cin >> Emp[i].hours;
}
cout << "\n*** Employee Details ***";
cout << "ID" << setw(15) << "First Name" << setw(10) << "Last Name" << setw(10) << "Pay" << setw(10) << "Hours" << setw(10) << "Gross Pay";
for (i = 0; i < n; i++) {
cout << "\n" << Emp[i].id << setw(15) << Emp[i].fName << setw(10) << Emp[i].lName << setw(10) << Emp[i].pay << setw(10) << Emp[i].hours << setw(10) << Emp[i].pay*Emp[i].hours;
}
_getch();
return 0;
}
Employee Emp[n];
In C/C++ you can't declare dynamic-size arrays like this.
See this question - How to create a dynamic array of integers
Or better, use an std::vector instead.
C++ standard requires you to provide an array size known at compile time.
Therefore to acquire what you want you need to use dynamic memory allocation i.e. allocate an array on heap depending upon the n being entered by the user. The following demonstrates this method.
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>
#include<iomanip>
using namespace std;
struct Employee
{
int id;
string fName;
string lName;
int pay;
int hours;
};
int main() {
int i, n;
cout << "Enter number of employees";
cin >> n;
auto *Emp = new Employee[n];
for (i = 0; i < n; i++) {
cout << "Enter Employee ID: ";
cin >> Emp[i].id;
cout << "Enter First Name: ";
cin >> Emp[i].fName;
cout << "Enter Last Name: ";
cin >> Emp[i].lName;
cout << "Enter in Pay Rate: ";
cin >> Emp[i].pay;
cout << "Enter in Hours: ";
cin >> Emp[i].hours;
}
cout << "\n*** Employee Details ***";
cout << "ID" << setw(15) << "First Name" << setw(10) << "Last Name" << setw(10) << "Pay" << setw(10) << "Hours" << setw(10) << "Gross Pay";
for (i = 0; i < n; i++) {
cout << "\n" << Emp[i].id << setw(15) << Emp[i].fName << setw(10) << Emp[i].lName << setw(10) << Emp[i].pay << setw(10) << Emp[i].hours << setw(10) << Emp[i].pay*Emp[i].hours;
}
delete [] Emp;
return 0;
}

How to use struct members in a struct's member function?

So the purpose of the program is to Create an array of 3 people, allow the user to populate the data in a for loop, ensure that the results are capitalized, and output the results.
These new projects instructions were to
1. Rewrite capitalize() as a method within the structure.
2. Rewrite printPerson() as a method within the structure
The program itself works just fine, it's just not in the format that my professor wanted. He said the point of it is to not use any arguments but again, I don't know what he means. I just started programming a few months ago and even though I'm trying I don't have a strong knowledge of the terminology.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person {
string firstName;
string middleName;
string lastName;
int age;
string gender;
void capitalize(Person &arg);
void printPerson(Person arg);
};
Pretty sure these are the methods right here, but I'm not sure if the (person &arg) and (person arg) are the arguments itself or if they are parameters. I thought it was the "arg" part but I can't find a way to get the program to run without them as I'm pretty sure I need the & of operator to modify the information.
int main(void) {
Person myPerson;
Person a[3];
const int size = 5;
for (int i = 0; i <= 2; i++) {
cout << "What is First Name #" << i + 1 << "? ";
getline(cin, a[i].firstName);
cout << "What is Middle Name #" << i + 1 << "? ";
getline(cin, a[i].middleName);
cout << "What is Last Name #" << i + 1 << "? ";
getline(cin, a[i].lastName);
cout << "Age #" << i + 1 << "? ";
cin >> a[i].age;
cin.ignore();
cout << "Male or Female #" << i + 1 << "? ";
getline(cin, a[i].gender);
cout << endl;
}
for (int i = 0; i <= 2; i++) {
myPerson.capitalize(a[i]);
cout << "PERSON #" << i + 1 << endl;
cout << "~~~~~~~~~~~~~~~" << endl;
myPerson.printPerson(a[i]);
}
system("pause");
return 0;
}
Along with that, I don't know how to manipulate the functions to work without the "parameters/arguments" (I'm not sure the difference at this point) or without the "arg"
void Person::capitalize(Person &arg) {
transform(arg.firstName.begin(), arg.firstName.end(), arg.firstName.begin(), ::toupper);
transform(arg.middleName.begin(), arg.middleName.end(), arg.middleName.begin(), ::toupper);
transform(arg.lastName.begin(), arg.lastName.end(), arg.lastName.begin(), ::toupper);
}
void Person::printPerson(Person arg) {
cout << "\nFirst Name: " << arg.firstName << endl;
cout << "\nMiddle Name: " << arg.middleName << endl;
cout << "\nLast Name: " << arg.lastName << endl;
cout << "\nAge: " << arg.age << endl;
cout << "\nGender: " << arg.gender << endl;
cout << "\n\n";
}
The capitalize and the printPerson are now members (usually called methods) of the struct Person. This means that they operate on the member variables of an Person instance. Like this, you can just access all the classes members in these methods. See the following code. I also completed it with a constructor and made it slightly more readable.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person {
public:
Person();
void readFromUserInput();
void capitalize();
void print();
public:
string firstName;
string middleName;
string lastName;
int age;
string gender;
};
Person::Person() :
firstName(""),
middleName(""),
lastName(""),
age(0),
gender("")
{
}
void Person::readFromUserInput()
{
cout << "What is the First Name ? ";
getline(cin, firstName);
cout << "What is Middle Name ? ";
getline(cin, middleName);
cout << "What is Last Name ? ";
getline(cin, lastName);
cout << "Age ? ";
cin >> age;
cin.ignore();
cout << "Male or Female ? ";
getline(cin, gender);
}
void Person::capitalize()
{
transform(firstName.begin(), firstName.end(), firstName.begin(), ::toupper);
transform(middleName.begin(), middleName.end(), middleName.begin(), ::toupper);
transform(lastName.begin(), lastName.end(), lastName.begin(), ::toupper);
}
void Person::print()
{
cout << "\nFirst Name: " << firstName << endl;
cout << "\nMiddle Name: " << middleName << endl;
cout << "\nLast Name: " << lastName << endl;
cout << "\nAge: " << age << endl;
cout << "\nGender: " << gender << endl;
cout << "\n\n";
}
int main(void)
{
const int NUM_PERSONS = 3;
Person a[NUM_PERSONS];
for (int i = 0; i < NUM_PERSONS; i++)
{
cout << "### " << (i + 1) << ". User:" << endl;
a[i].readFromUserInput();
cout << endl;
}
for (int i = 0; i < NUM_PERSONS; i++)
{
a[i].capitalize();
cout << "PERSON #" << i + 1 << endl;
cout << "~~~~~~~~~~~~~~~" << endl;
a[i].print();
}
system("pause");
return 0;
}

Changing struct into class C++ [closed]

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
For my homework assignment, I was supposed to code a struct that collected information about music albums. I was able to do this easily. The second part of my assignment was to turn my struct into a class, and I'm having trouble getting my code to compile. Here are my two codes.
Struct code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Date
{
int month;
int day;
int year;
};
struct Album
{
string name;
string artist;
vector <string> songs;
Date release;
};
void initializeAlbum(Album& a);
void initializeSongs(vector <string> & songs);
void printAlbum(Album a);
int main()
{
Album my_album;
initializeAlbum(my_album);
printAlbum(my_album);
return 0;
}
void initializeAlbum(Album& a)
{
cout << "Enter album name:" << endl;
getline(cin, a.name);
cout << "Enter artist name:" << endl;
getline(cin, a.artist);
cout << "Enter the release month (numeric format: ex. 06/10/1995):" << endl;
cin >> a.release.month;
cout << "Enter the release day:" << endl;
cin >> a.release.day;
cout << "Enter the release year:" << endl;
cin >> a.release.year;
initializeSongs(a.songs);
}
void initializeSongs(vector <string> & songs)
{
cout << "How many songs are in the album?" << endl;
int j = 0;
cin >> j;
string answer;
cout << "Enter each song name one at a time:" << endl;
for ( int y = 0; y <= j; y++)
{
getline (cin, answer);
songs.push_back(answer);
}
}
void printAlbum(Album a)
{
cout << "The album name is " << a.name << endl;
cout << "The artist name is " << a.artist << endl;
cout << "The release date is " << a.release.day << "/" << a.release.month << "/" << a.release.year << endl;
cout << "The songs are:";
for (int x = 0; x < a.songs.size(); x++ )
cout << " " << a.songs[x] << endl;
}
Class code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Date
{
int month;
int day;
int year;
};
class Album
{
public:
void printAlbum();
void initializeAlbum();
string name;
string artist;
vector <string> songs;
Date release;
private:
void initializeSongs();
};
int main()
{
Album a;
a.initializeAlbum();
a.printAlbum();
return 0;
}
void Album::initializeAlbum( )
{
cout << "Enter album name:" << endl;
getline(cin, name);
cout << "Enter artist name:" << endl;
getline(cin, artist);
cout << "Enter the release month (numeric format: ex. 06/10/1995):" << endl;
cin >> release.month;
cout << "Enter the release day:" << endl;
cin >> release.day;
cout << "Enter the release year:" << endl;
cin >> release.year;
initializeSongs(songs);
}
void Album::initializeSongs()
{
cout << "How many songs are in the album?" << endl;
int j = 0;
cin >> j;
string answer;
cout << "Enter each song name one at a time:" << endl;
for ( int y = 0; y <= j; y++)
{
getline (cin, answer);
songs.push_back(answer);
}
}
void Album::printAlbum()
{
cout << "The album name is " << name << endl;
cout << "The artist name is " << artist << endl;
cout << "The release date is " << release.day << "/" << release.month << "/" << release.year << endl;
cout << "The songs are:";
for (int x = 0; x < songs.size(); x++ )
cout << " " << songs[x] << endl;
}
Maybe this line is your error: initializeSongs(songs); in void Album::initializeAlbum() function?
Follow compiler messages.
This function takes zero arguments:
void Album::initializeSongs()
{
cout << "How many songs are in the album?" << endl;
int j = 0;
cin >> j;
string answer;
cout << "Enter each song name one at a time:" << endl;
for ( int y = 0; y <= j; y++)
{
getline (cin, answer);
songs.push_back(answer);
}
}
Yet you call
initializeSongs(songs);
You can access your members within your class functions so just call it like:
initializeSongs();
This compiles fine:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Date
{
int month;
int day;
int year;
};
class Album
{
public:
void printAlbum();
void initializeAlbum();
string name;
string artist;
vector <string> songs;
Date release;
private:
void initializeSongs();
};
int main()
{
Album a;
a.initializeAlbum();
a.printAlbum();
return 0;
}
void Album::initializeAlbum( )
{
cout << "Enter album name:" << endl;
getline(cin, name);
cout << "Enter artist name:" << endl;
getline(cin, artist);
cout << "Enter the release month (numeric format: ex. 06/10/1995):" << endl;
cin >> release.month;
cout << "Enter the release day:" << endl;
cin >> release.day;
cout << "Enter the release year:" << endl;
cin >> release.year;
initializeSongs();
}
void Album::initializeSongs()
{
cout << "How many songs are in the album?" << endl;
int j = 0;
cin >> j;
string answer;
cout << "Enter each song name one at a time:" << endl;
for ( int y = 0; y <= j; y++)
{
getline (cin, answer);
songs.push_back(answer);
}
}
void Album::printAlbum()
{
cout << "The album name is " << name << endl;
cout << "The artist name is " << artist << endl;
cout << "The release date is " << release.day << "/" << release.month << "/" << release.year << endl;
cout << "The songs are:";
for (int x = 0; x < songs.size(); x++ )
cout << " " << songs[x] << endl;
}