// The function which i was required to make was to.string() in the class,Which i had no idea how to make.This is an odd function(not comparing with the math one.)which returns value in two different types of data types i.e(string,integer).The only thing stuck me was assigning a variable after making (string to.string()) function//The return value of function is something like
[age,first_name,last_name,standard](without the square brackets with the commmasin the output)
p.s=need a simpler function without using vector header.
#include <iostream>
#include <sstream>
using namespace std;
class Student{
public :
void set_age(int no){
age_no=no;
}
void set_standard(int no){
std_no=no;
}
void set_first_name(string identity){
name_letter=identity;
}
void set_last_name(string identity2){
last_name_letter = identity2;
}
int get_age(){
return age_num;
}
int get_standard(){
return std_no;
}
string get_first_name(){
return name_letter;
}
string get_last_name(){
return last_name_letter;
}
private :
int age_no;
int std_no;
string name_letter;
string last_name_letter;
};
int main() {
int age, standard;
string first_name, last_name;
cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
cout << st.get_age() << "\n";
cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
cout << st.get_standard() << "\n";
cout << "\n";
cout << st.to_string();
return 0;
}
If you want to create a string with the format age, first_name, last_name, standard then you could do something like
class Student
{
public:
...
std::string to_string() const;
...
};
std::string Student::to_string() const
{
return std::to_string(get_age()) + ", " +
get_first_name() + ", "
get_last_name() + ", "
std::to_string(get_standard());
}
As an aside, I would suggest making all of your getter functions const for example
int get_age() const;
This denotes that the method will not mutate or modify any of the values of the class's member variables.
Related
I am doing a practice problem in HackerRank, and I am having trouble implementing the final task for this one issue I am having with classes.
It is a pretty simple program, it just uses a Student class with setter and getter functions to take in a student's information (age, firstname, lastname, and academic standard), and uses an stringstream to output that data.
However, at the very end is where I am having trouble. I am supposed to create a to_string() function which returns a string consisting of the above elements, separated by a comma (,). I think I am just mis-understanding how to use ostringstream.
#include <iostream>
#include <sstream>
#include <string>
class Student{
private:
int age;
std::string first_name;
std::string last_name;
int standard;
public:
void set_age(int age){
age = age;
}
int get_age(){
return age;
}
void set_standard(int standard){
standard = standard;
}
int get_standard(){
return standard;
}
void set_first_name(std::string first_name){
first_name = first_name;
}
std::string get_first_name(){
return first_name;
}
void set_last_name(std::string last_name){
last_name = last_name;
}
std::string get_last_name(){
return last_name;
}
std::string to_string(){
std::stringstream os;
os << age << "," << first_name << "," << last_name << "," << standard << std::endl;
return os.str();
}
};
int main() {
int age, standard;
std::string first_name, last_name;
std::cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
std::cout << st.get_age() << "\n";
std::cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
std::cout << st.get_standard() << "\n";
std::cout << "\n";
std::cout << st.to_string();
return 0;
}
Input Example:
15
john
carmack
10
Expected output:
15
carmack, john
10
15,john,carmack,10
My output:
2
,
0
2,,,0
All of your class setters suffer from the same problem - each input parameter has the same name as its corresponding class member. As such, each parameter is shadowing the class member, so you end up assigning the input value back to the parameter, rather than to the class member.
Thus, none of your class members are actually being assigned any input values at all, which is why you are getting garbage in your output.
Once you fix the shadowing issue, you will get your expected output:
void set_age(int /*age*/value){
age = /*age*/value;
}
...
void set_standard(int /*standard*/value){
standard = /*standard*/value;
}
...
void set_first_name(std::string /*first_name*/value){
first_name = /*first_name*/value;
}
...
void set_last_name(std::string /*last_name*/value){
last_name = /*last_name*/value;
}
...
On a side note: to_string() should use std::ostringstream instead of std::stringstream. And to_string(), and all of the getters, should be marked as const, since they aren't modifying the Student object.
Online Demo
Entry point is int main() so I try summon pwr.GetSalary to cout outside string "Salary" and double value, however program does not print out anything.
So it is base class.
class Employee
{
public:
std::string FirstName;
std::string LastName;
std::string Patronymic;
double Salary;
Employee() {};
explicit Employee(std::string FirstName, std::string LastName,
std::string Patronymic, double Salary)
: FirstName(FirstName), LastName(LastName),
Patronymic(Patronymic), Salary(Salary) {}
bool operator==(Employee other) const
{
if (this->FirstName == other.FirstName &&
this->LastName == other.LastName &&
this->Patronymic == other.Patronymic)
return true;
else
return false;
}
};
An daughter class that inherits base class... Here is wonderful method that shall count a salary and print it out...
class Papersworker : public Employee
{
private:
std::string FirstName;
std::string LastName;
std::string Patronymic;
double Salary;
public:
Papersworker() {};
using Employee::Employee;
const std::string Job = "Papersworker";
std::map<std::string, double> Coefficient =
{
{"Director", 4.2},
{"Papersworker", 1.2},
{"Guardian", 1.5},
{"Programmer", 2.5}
};
void ChangeCoefficient(std::string Job, double NewCoefficient)
{
Coefficient[Job] = NewCoefficient;
}
void ChangeNameSalary(std::string FirstName, std::string LastName, std::string Patronymic, double Salary)
{
this->FirstName = FirstName;
this->LastName = LastName;
this->Patronymic = Patronymic;
this->Salary = Salary;
}
void PrintPapersworker()
{
std::cout << "First name\t" << "Lastname\t" << "Patronymic\t" << "Salary\n" << this->FirstName << "\t\t" << this->LastName << "\t" << this->Patronymic << "\t" << this->Salary << "\n" << std::flush;
for (const auto& i : this->Coefficient)
{
std::cout << i.first << " = " << i.second << ";\t" << std::flush;
}
std::cout << "\n------------------------------------------------------------\n" << std::flush;
}
double GetSalary(double Salary, std::string Job)
{
return Salary * this->Coefficient[Job];
}
};
Wonderful int main()'s part.
int main()
{
Papersworker pwr;
double sr = 0.0;
std::cout << "\nEnter director's salary\t" << std::flush; std::cin >> sr;
std::cout << "\nSalary\t" << pwr.GetSalary(sr, "Director");
return 0;
}
If you see a some bad and need optimization don't mind to reply. ._. I do not understand what is going on there in matter of classes building tricks. https://pastebin.com/p7HXaX80
P. S. My homework forces to use private FirstName,LastName,Patronymic,salary...
P. S. S. However, I use Visual Studio 2022 Preview with newest C++ nowadays.
https://imgur.com/a/N8cDK3n
program does not print out anything
Your program(pastebin link you gave) compiles successfully and prints continuously if you change _getch() to getch() as can be seen here. But for some reason it goes on forever. Since the link that you gave have around 500 lines of code i didn't take a look as to why the condition is not breaking(or if the program has any undefined behavior). Maybe you can narrow down the problem and edit your question again.
Your code will not compile as sr variable is not defined.
Define double sr; before using it in main()'s statement std::cin >> sr; and (at least) the program will compile and interact with the user.
int main() {
Papersworker pwr;
std::cout << "\nEnter director's salary\t" << std::flush;
double sr; // <- your missed variable
std::cin >> sr;
std::cout << "\nSalary\t" << pwr.GetSalary(sr, "Director");
}
Program's prints with input 10:
Enter director's salary 10
Salary 42
All of the private members of Papersworker shadow the public members from Employee
class Papersworker : public Employee {
private:
std::string FirstName;
std::string LastName;
std::string Patronymic;
double Salary;
// ...
};
Try this: Compiler Explorer (Untested ’cause I’m in a rush right now, I’ll look at it when I come back)
Also, be careful with std::map::operator []
This is an assignment of mine that I picked to do but I am not sure how to fix the error message I am getting at cout << contact.getInformation() << endl;without changing the Void function to a different type or changing the main function (which I am trying to avoid). I think my lack of understanding is in how cout and void functions work together. I tried to remove the cout from the function but that did not work and the only way I could make the code run was when I replaced cout << contact.getInformation() << endl; with contact.getInformation() which I am trying to avoid. I just want the inside of the void function to print when I call cout << contact.getInformation() << endl;
Any help is welcome! Thank you!
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
class Contact{
public:
Contact(int id, string name, string telephone, int age)
: _id{ id }, _name{ name }, _telephone{ telephone }, _age{ age } {}
int id() { return _id; }
string name() { return _name; }
string telephone() { return _telephone; }
int age() { return _age; }
void getInformation() {
cout << "ID: " + to_string(_id) + "\n" +
"NAME: " + _name + "\n" +
"TEL: " + _telephone + "\n" +
"AGE: " + to_string(_age) + "\n";
}
private:
int _id;
string _name;
string _telephone;
int _age;
};
int main() {
Contact contact{1, "Michael", "555-555-5555", 15};
cout << contact.getInformation() << endl;
}.
EDIT: Thanks all! I see now that it is impossible to do with those restrictions.
The code you've provided have many issues. You can avoid them if you read some good C++ book, my advice is Scott Meyers Effective C++: 55 Specific Ways to Improve Your Programs and Designs.
don't use using directive unless really necessary. In most cases for std namespace - it is not.
Pass function arguments of non primitive type by reference/const reference rather by value or pointer
Understand const keyword and it usage
Understand constructor static initialization bocks
Understand c++ streams
This is how you code should looks like:
#include <iostream>
#include <string>
class Contact {
public:
Contact(int id,const std::string& name,const std::string& telephone, int age):
_id( id ),
_name( name ),
_telephone( telephone ),
_age( age )
{}
int id() const {
return _id;
}
std::string name() const {
return _name;
}
std::string telephone() const {
return _telephone;
}
int age() const {
return _age;
}
private:
int _id;
std::string _name;
std::string _telephone;
int _age;
};
std::ostream& operator<<(std::ostream& to,const Contact& c)
{
to << "ID: " << c.id() << '\n';
to << "NAME: " << c.name() << '\n';
to << "TEL: " << c.telephone() << '\n';
to << "AGE: " << c.age() << '\n';
to.flush();
return to;
}
int main(int argc, const char** argv)
{
Contact contact = {1, "Michael", "555-555-5555", 15};
std::cout << contact << std::endl;
return 0;
}
What you are asking is not possible. The two conditions you have set (i.e. 1. Do not change the void function to another type, and 2. Do not alter the main method) make it impossible to change your code in some other way so as for the main function to produce the intended outcome.
You can either alter your void function to one that returns something 'printable', e.g. a string, or you can keep your void function printing to cout directly, but then change the main function to call this on its own, outside the context of a cout << construct.
(Or, preferably, as has also been pointed in the comments, instead of void, overload the << operator to make cout work with your specific object type)
The name getInformation suggests it should, well, get the information and not print it.
Therefore you probably want this:
string getInformation() {
return "ID: " + to_string(_id) + "\n" +
"NAME: " + _name + "\n" +
"TEL: " + _telephone + "\n" +
"AGE: " + to_string(_age) + "\n";
}
Instead of this:
void getInformation() {
cout << "ID: " + to_string(_id) + "\n" +
"NAME: " + _name + "\n" +
"TEL: " + _telephone + "\n" +
"AGE: " + to_string(_age) + "\n";
}
Not changing main nor getInformation is not possible.
I am trying to create a program that uses class, arrays, and functions to show information about two students(Name, id#, classes registered). The part I am struggling with is passing arrays to a function. How do I do that?
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
class Student // Student class declaration.
{
private:
string name;
int id;
string classes;
int arraySize;
public:
void setName(string n)
{
name = n;
}
void setId(int i)
{
id = i;
}
void setClasses(string c, int num)
{
classes = c;
arraySize = num;
}
string getName()
{
return name;
}
int getId()
{
return id;
}
void getClasses()
{
for (int counter=0; counter <arraySize; counter++) {
cout << classes[counter] << endl;
}
}
};
int main()
{
//Student 1
string s1Name = "John Doe";
int s1Id = 51090210;
int const NUMCLASSES1 = 3;
string s1Classes[NUMCLASSES1] = {"C++","Intro to Theatre","Stagecraft"};
//Student 2
string s2Name = "Rick Harambe Sanchez";
int s2Id = 666123420;
int const NUMCLASSES2 = 2;
string s2Classes[NUMCLASSES2] = {"Intro to Rocket Science","Intermediate Acting"};
//
Student info;
info.setName(s1Name);
info.setId(s1Id);
//info.setClasses(s1Classes, NUMCLASSES1);
cout << "Here is Student #1's information:\n";
cout << "Name: " << info.getName() << endl;
cout << "ID: " << info.getId() << endl;
//cout << "Classes: " << info.getClasses() << endl;
info.setName(s2Name);
info.setId(s2Id);
// info.setClasses(s2Classes, NUMCLASSES1);
cout << "\n\nHere is student #2's information:\n";
cout << "Name: " << info.getName() << endl;
cout << "ID: " << info.getId() << endl;
//cout << "Classes: " << info.getClasses() << endl;
return 0;
}
The usual way to pass around variable-length lists in C++ is to use an std::vector. A vector is a single object that you can easily pass to a function, copying (or referencing) its contents. If you are familiar with Java, it's basically an ArrayList. Here is an example:
#include <vector>
#include <string>
using namespace std;
class foo {
private:
vector<string> myStrings;
public:
void setMyStrings(vector<string> vec) {
myStrings = vec;
}
}
//...
foo myObj;
vector<string> list = {"foo","bar","baz"};
myObj.setMyStrings(list);
If don't want to use the standard library though, you can pass an array C-style. This involves passing a pointer to the first element of the array, and the length of the array. Example:
void processStrings(string* arr, int len) {
for (int i = 0; i < len; i++) {
string str = arr[i];
//...
}
}
string array[] = {"foo","bar","baz"};
processStrings(array, 3); // you could also replace 3 with sizeof(array)
Passing raw arrays like this, especially if you wanted to then copy the array into an object, can be painful. Raw arrays in C & C++ are just pointers to the first element of the list. Unlike in languages like Java and JavaScript, they don't keep track of their length, and you can't just assign one array to another. An std::vector encapsulates the concept of a "list of things" and is generally more intuitive to use for that purpose.
Life lesson: use std::vector.
EDIT: See #nathanesau's answer for an example of using constructors to initialize objects more cleanly. (But don't copy-paste, write it up yourself! You'll learn a lot faster that way.)
You can pass array of any_data_type to function like this
void foo(data_type arr[]);
foo(arr); // If you just want to use the value of array
foo(&arr); // If you want to alter the value of array.
Use std::vector. Also, don't add functions you don't need. Here's an example of using std::vector
#include <string>
#include <iostream>
#include <vector>
using std::string;
using std::vector;
class Student // Student class declaration.
{
private:
vector<string> classes;
string name;
int id;
public:
Student (const vector<string> &classesUse, string nameUse, int idUse) :
classes (classesUse),
name (nameUse),
id (idUse)
{
}
void print ()
{
std::cout << "Name: " << name << std::endl;
std::cout << "Id: " << id << std::endl;
std::cout << "Classes: ";
for (int i = 0; i < classes.size (); i++)
{
if (i < classes.size () - 1)
{
std::cout << classes[i] << ", ";
}
else
{
std::cout << classes[i] << std::endl;
}
}
std::cout << std::endl;
}
};
int main()
{
Student John ({"C++","Intro to Theatre","Stagecraft"},
"John",
51090210);
John.print ();
Student Rick ({"Intro to Rocket Science","Intermediate Acting"},
"Rick",
666123420);
Rick.print ();
return 0;
}
Name: John
Id: 51090210
Classes: C++, Intro to Theatre, Stagecraft
Name: Rick
Id: 666123420
Classes: Intro to Rocket Science, Intermediate Acting
In the private variables of class Student, you are storing a string:
String classes;
where as you should be storing an array of strings like:
String classes[MAX_NUM_CLASSES];
then in the set classes function, pass in an array of strings as the first argument, so it should be :
void setClasses(string[] c, int num)
{
classes = c; //not sure if simply setting them equal will work, rather copy entire array using a for loop
arraySize = num;
}
This should point you in the right direction
Also, use std::vector instead of string[], it will be easier.
Good afternoon!
Sorry if the question seems rather vague, but here's some (incomplete) code for some context. Specifically, this is about the "UserInfo inputInfo" definition part as seen in the functions UserInfo::setUserInfo() and UserInfo::displayProfile() in the implementation file.
project02.cpp (implementation file)
#include <iostream>
#include "project02.h"
using namespace std;
void UserInfo::setUserInfo()
{
UserInfo inputInfo;
string fName;
string lName;
int bYear;
string city;
string occupation;
cout << "Please enter your first name: ";
cin >> fName;
inputInfo.setFirstName(fName);
cout << "Please enter your last name: ";
cin >> lName;
inputInfo.setLastName(lName);
cout << "You are now registered as: " << inputInfo.getFirstName() << " " << inputInfo.getLastName();
}
void UserInfo::displayProfile()
{
UserInfo inputInfo;
cout << "Profile Information:" << endl;
cout << "Name: " << inputInfo.getFirstName() << " " << inputInfo.getLastName();
}
void UserInfo::setFirstName(string fName)
{
_firstName = fName;
}
string UserInfo::getFirstName()
{
return _firstName;
}
void UserInfo::setLastName(string lName)
{
_lastName = lName;
}
string UserInfo::getLastName()
{
return _lastName;
}
project02.h (header file)
#ifndef PROJECT02_H
#define PROJECT02_H
using namespace std;
class UserInfo
{
public:
string getFirstName();
void setFirstName(string first);
string getLastName();
void setLastName(string last);
int getBirthYear();
void setBirthYear(int year);
string getCurrentCity();
void setCurrentCity(string city);
string getOccupation();
void setOccupation(string occ);
void setUserInfo();
void displayProfile();
private:
string _firstName;
string _lastName;
int _birthYear;
string _currentCity;
string _occupation;
};
#endif // PROJECT02_H
project02main.cpp (main file)
#include <iostream>
#include "project02.h"
using namespace std;
int main()
{
UserInfo inputInfo;
inputInfo.setUserInfo();
return 0;
}
Now the question is: is there an alternative to repeatedly defining the object "UserInfo inputInfo;" each time for a different function in the implementation file?
Don't create objects of the same data type within methods of that datatype at this point - simply call setFirstname() and getFirstname() to use methods that will modify the same object that you are currently using.