C++ How to call a void function without errors? - c++

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.

Related

.Can there be a easier function defining - (to.string()) below

// 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.

Error on my first class when trying to display

I'm building a class that will create a vehicle's characteristics and I'm having some difficulties when trying to display autovehicle a1 on the console. I get an error which I cannot explain. Please help, if possible
#include <iostream>
using namespace std;
class Autovehicle {
private:
//registry number
char * car_registration_number;
char engine;
int engine_cc;
int avg_consumption;
int avg_speed;
int avg_consumption_urban;
int avg_speed_urban;
int max_speed;
static int number_of_autovehicles;
public:
//getters
char * get_car_registration_number() {
return this->car_registration_number;
}
char get_engine()
{
return this->engine;
}
int get_engine_cc() {
return this->engine_cc;
}
int get_avg_consumption() {
return this->avg_consumption;
}
int get_avg_speed() {
return this->avg_speed;
}
int get_avg_consumption_urban() {
return this->avg_consumption_urban;
}
int get_avg_speed_urban() {
return this->avg_speed_urban;
}
int get_max_speed() {
return this->max_speed;
}
static int get_number_of_cars() {
return number_of_autovehicles;
}
//setters
void set_car_registration_number(char *car_reg_nr) {
this->car_registration_number = car_reg_nr;
}
void set_engine(char eng) {
this->engine = eng;
}
void set_engine_cc(int eng_cc) {
this->engine_cc = eng_cc;
}
void set_avg_consumption(int avg_cons) {
this->avg_consumption = avg_cons;
}
void set_avg_speed(int avg_spd) {
if (this->avg_speed > avg_spd)
cout << endl << "You should probably slow down";
this->avg_speed = avg_spd;
}
void set_avg_consumption_urban(int avg_cons_urb) {
this->avg_consumption_urban = avg_cons_urb;
}
void set_avg_speed_urban(int avg_spd_urb) {
if (this->avg_speed_urban > avg_spd_urb)
cout << endl << "You should probably slow down";
this->avg_speed_urban = avg_spd_urb;
}
void set_max_speed(int max_spd) {
this->max_speed = max_spd;
}
//default constructor
Autovehicle(){
number_of_autovehicles++;
this->car_registration_number = new char[strlen("There are no autovehicles") + 1];
strcpy(this->car_registration_number, "There are no autovehicles");
this->engine = NULL;
this->engine_cc = 0;
this->avg_consumption = 0;
this->avg_speed = 0;
this->avg_consumption_urban = 0;
this->avg_speed_urban = 0;
this->max_speed = 0;
}
//constructor
Autovehicle(char* car_reg_nr, char eng, int eng_cc, int avg_cons, int avg_spd, int avg_cons_urb, int avg_spd_urb, int max_spd){
number_of_autovehicles++;
this->car_registration_number = new char[strlen(car_reg_nr) + 1];
strcpy(this->car_registration_number, car_reg_nr);
this->engine = eng;
this->engine_cc = eng_cc;
this->avg_consumption = avg_cons;
this->avg_speed = avg_spd;
this->avg_consumption_urban = avg_cons_urb;
this->avg_speed_urban = avg_spd_urb;
this->max_speed = max_spd;
}
//destructor
~Autovehicle() {
delete[]this->car_registration_number;
number_of_autovehicles--;
}
};
This is where the void main, and the problem starts:
void main() {
Autovehicle a1( "Engniasd", "gasoline", 1980, 11, 50, 8, 100) {
cout<<"registration number: "<< this->car_registration_number;
cout << "engine: " << this->engine;
cout << "engine cc:" << this->engine_cc;
cout << "consumption: " << this->avg_consumption;
cout << "avg speed: " << this->avg_speed;
cout << "urban consumption: " << this->avg_consumption_urban;
cout << "urban speed " << this->avg_speed_urban;
}
}
The problem that I'm getting is "No instance of constructor matches the argument list" when trying to display Autovehicle a1(Engniasd, the first term)
Try to add the registration number to your car and the number of vehicles:
Autovehicle a1("REG12345", "gasoline", 1980, 11, 50, 8, 100, 50, 3).
Your constructor defines eng as a char, but you're passing it "gasoline" which is a const char*.
Also, storing the car registration number as a char*. Make your life easier and use a std::string instead. That way you, and your class users, don't need to worry about managing the lifetime of the pointer.
And, in main you've declared a variable called a1 but it looks like you are trying to call methods on it using this. You need to call against the instance variable:
cout << "engine: " << a1.engine;
You also need to terminate the a1 declaration with a semicolon and don't need the braces, eg:
Autovehicle a1( "Engniasd", "gasoline", 1980, 11, 50, 8, 100);
cout << "registration number: "<< a1.car_registration_number;
At school atm and unable to get a good look at this, but look at your constructor, you have a char instead of a char ptr for your 2nd argument. you can't implicitly convert char to const char*, you can char* -> const char*, so change your 2nd argument to a char*. Also, change void main() to int main(), main is supposed to be an int (ansi standard), and many compilers might not accept you using void main().
I see several problems.
Can you explain why car_registration_number and engine have different types?
If you can answer this one for yourself, you can fix one of your issues.
Also you should separate the class declaration from the implementation and make sure that you initialize all the variables. Including the static one.
Problems in calling constructor
Autovehicle(char* , char , int, int, int, int, int, int)
the second parameter is char, but you pass char*, also constructor have 6 int parameters, but you pass only five in main. And you cannot print values of object in your way. Create function in you class
void print()
{
cout<<"registration number: "<< this->car_registration_number;
cout << "engine: " << this->engine;
cout << "engine cc:" << this->engine_cc;
cout << "consumption: " << this->avg_consumption;
cout << "avg speed: " << this->avg_speed;
cout << "urban consumption: " << this->avg_consumption_urban;
cout << "urban speed " << this->avg_speed_urban;
}
and call it in main() as
Autovehicle a1( "Engniasd", "gasoline", 1980, 11, 50, 8, 100, 0);
a1.print();

Error reporting only once

I'm writing some code which handles a lot of data. When an error occures, it usually happens that the error will occur many times, so I want to report it only once. The problem I have is, that I want to have individual error messages. In C I would use a method with variadic arguments, bit of course this is not really typesafe, so I wonder how I can achieve the same in C++ with typesafe output. I know that I can stringstream and create the indvidual string, but that would mean that I have to create the full error message, even if it is discarded, because it was already printed, and stringstream is not exactly fast either.
So currently I use code like this:
std::string key = "BT:EMPTY";
if(mErrorReport.find(key) == mErrorReport.end())
{
std::cerr << "ERROR [" << Name<< "] Type is empty! " << std::endl;
mErrorReport.insert(key);
}
std::string key = "UI:"+Unitcode;
if(mErrorReport.find(key) == mErrorReport.end())
{
std::cerr << "ERROR [" << Name<< "] Room with the id " << Unitcode << " doesn't exist! " << std::endl;
mErrorReport.insert(key);
}
...
In C I would have written a variadic function like this:
void ErrorLog(const char *key, int nLogLevel, const char fmt, ...)
{
// Check if this error was already reported before.
if(mErrorLog.find(key) == mErrorLog.end())
{
fprintf(stderr, fmt, ...);
mErrorLog.insert(key);
}
}
So I wonder if there is some best practice for something like that.
Why don't you just use
void ErrorLog(const std::string& key, const std::string& name, const std::string& what)
{
if (mErrorLog.find(key) == mErrorLog.end())
{
std::cerr << "ERROR[" << name << "]" << what << std::endl;
mErrorLog.insert(key);
}
}
and call it like
ErrorLog("BT:EMPTY", Name, "Type is empty!");
ErrorLog("UI:" + Unitcode, Name, std::string("Room with the id ") + Unitcode + " doesn't exist!");
If Name doesn't change you could remove the parameter and just add it to the std::err call.
Update: Alternative solution
class ErrorLogWriter
{
public:
ErrorLogWriter(const std::string& name, const std::string& key, std::set<std::string>& log)
:m_name(name)
, m_key(key)
, m_log(log)
{}
ErrorLogWriter& operator<<(const std::string& msg)
{
if (m_log.find(m_key) == m_log.end())
{
std::cerr << "ERROR[" << m_name << "]" << msg << std::endl;
m_log.insert(m_key);
}
return *this;
}
private:
std::string m_name;
std::string m_key;
std::set<std::string>& m_log;
};
class ErrorLog
{
public:
ErrorLog(const std::string& name, std::set<std::string>& log)
:m_name(name)
,m_log(log)
{}
ErrorLogWriter operator()(const std::string& key)
{
return ErrorLogWriter(m_name, key, m_log);
}
private:
std::string m_name;
std::set<std::string>& m_log;
};
int main()
{
std::string Name = "NAME";
std::string Unitcode = "UNITCODE";
std::set<std::string> mErrorLog;
ErrorLog log(Name, mErrorLog);
log("BT:EMPTY") << "Type is empty!";
log("UI:" + Unitcode) << "Room with the id " << Unitcode << " doesn't exist!";
}

C++ Expression must be a modifiable lvalue

writing this program for my c++ class and im running into an issue. My program reads the inputtted name and stores it into name it then wants to check for correct parameters under _name.. here are my class and its header file.
My error is specifically under ::setName where i want to check or set my inputted name with _name for correct output under ::display()
PhoneNumber.cpp
using namespace oop244;
void PhoneNumber::display() const{
cout << "name: " << _name << ", Phone number: (" << _areacode << ") " << _localNumber / 10000 << "-" << _localNumber % 10000 << endl;
}
bool PhoneNumber::isValid() const
{
if (correctNum == false && correctArea == false){
cout << _name << " does not have a valid phone number." << endl;
return false;
}
else{
return true;
}
}
void PhoneNumber::setName(const char name[])
{
cout << name << endl;
_name = name;
}
PhoneNumber.h
#define MAX_NAME_LENGTH 40
#define PHNO_MAX 999999
#define PHNO_MIN 100000
#define AREACODE_MIN 100
#define AREACODE_MAX 999
namespace oop244{
class PhoneNumber{
private:
char _name[MAX_NAME_LENGTH + 1];
int _areacode;
int _localNumber;
bool _validPhoneNumber;
public:
void setName(const char name[]);
void setPhoneNumber(int areaCode, int number);
void display() const;
bool isValid() const;
};
};
use standard string
#include <string>
and use
std::string _name;
in your class declarations instead of
char _name[MAX_NAME_LENGTH + 1];
alternatively use c-style str-functions, as suggested in another answer
You can't assign raw arrays. You need to copy the contents.
Assuming your class teacher forces you to use char arrays, you can for example use strncpy to copy the characters:
strncpy(_name, name, MAX_NAME_LENGTH);
You need to #include <cstring> for this.
If your class teacher allows it, better use std::array<char,MAX_NAME_LENGTH> or even std::string. Both can be copied by assigning.

Putting a value to ostream

I have this code below which parses a for statement, but I am not sure how to put any value into the ostream when calling the method write(...). What can I do? (e.g write("for (........."))
#include <ostream>
#include <iostream>
using namespace std;
//I cut out the declaration bit here
typedef const string type;
private:
type *initializer;
type *condition;
type *increment;
type *body;
public:
void write(ostream& stream) const {
stream
<< "for ("
<< *initializer << "; "
<< *condition << "; "
<< *increment << ")\n{\n"
<< *body
<< "}";
}
I guess you try to learn using ostream as an input in a function. But it seems that you mixing things that how to use classs and methods.
Maybe this is no avail but i can give you a little snippet to give you some opinion.
#include <iostream>
#include <string>
using namespace std;
typedef const string type;
type *init;
type *cond;
type *incr;
type *body;
void write(ostream& stream) {
stream
<< "for ("
<< *init << "; "
<< *cond << "; "
<< *incr << ")\n{\n"
<< *body
<< "\n}";
}
int main(int argc, char* argv[])
{
const string ini = "int i = 0";
const string con = "i < 10";
const string inc = "i++";
const string bod = "cout << i << endl;";
init = &ini;
cond = &con;
incr = &inc;
body = &bod;
write(cout);
return 0;
}
Try this code, examine and read more for more details.