// Function displays course information
// instructor defaults to Staff
// enrollment defualts to 30
// main() demonstrates function can be called three ways
#include<iostream>
using namespace std;
int main()
{
void displayCourseInfo(char, char* = "Staff", int = 30);
displayCourseInfo("ENG101");
displayCourseInfo("PSY151", "Bossert");
displayCourseInfo("CIS200", "Edwards", 24);
return 0;
}
void displayCourseInfo(char course, char* instructor, int enrollment)
{ cout << course << " taught by " << instructor <<
" enrollment " << enrollment << endl;
}
When I try to run this code I get
this error message. It says that I cannot convert *const char to char.
Thank you for your time and help.
String literals in C++ (opposite to C) have types of constant character arrays. For example the string literal "Staff" has the type const char [6].
Used in expressions array designators with rare exceptions are converted to pointers to their first elements. So the string literal "Staff" used as an argument is converted to a pointer of the type const char *.
The first parameter of the function displayCourseInfo is declared as having the type char while you are trying to pass a string literal as an argument.
A valid program can look the following way
// Function displays course information
// instructor defaults to Staff
// enrollment defualts to 30
// main() demonstrates function can be called three ways
#include<iostream>
using namespace std;
int main()
{
void displayCourseInfo( const char *, const char * = "Staff", int = 30 );
displayCourseInfo("ENG101");
displayCourseInfo("PSY151", "Bossert");
displayCourseInfo("CIS200", "Edwards", 24);
return 0;
}
void displayCourseInfo( const char *course, const char *instructor, int enrollment)
{
cout << course << " taught by " << instructor
<< " enrollment " << enrollment << endl;
}
Its output is
ENG101 taught by Staff enrollment 30
PSY151 taught by Bossert enrollment 30
CIS200 taught by Edwards enrollment 24
This happens because "test in quotes" is by default const char*.
Values with const in their declaration cannot be changed.
You can't pass const variable to function that takes non-const parameters.
You could just make function's parameters const:
#include<iostream>
using namespace std;
void displayCourseInfo(const char *);
void displayCourseInfo(const char *, const char *);
void displayCourseInfo(const char *, const char *, const int);
int main() {
displayCourseInfo("ENG101");
displayCourseInfo("PSY151", "Bossert");
displayCourseInfo("CIS200", "Edwards", 24);
return 0;
}
void displayCourseInfo(const char *course, const char *instructor) {
cout << course << " taught by " << instructor <<
" enrollment " << 30 << endl;
}
void displayCourseInfo(const char *course) {
cout << course << " taught by " << "Staff" <<
" enrollment " << 30 << endl;
}
void displayCourseInfo(const char *course, const char *instructor, const int enrollment) {
cout << course << " taught by " << instructor <<
" enrollment " << enrollment << endl;
}
Related
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 have the task to write a function char * stringReplace(const char * str, const char * what, const char * with) which replaces "what" with "with" on a new string with the correct length. So Inside the function I created dynamic array, which the function returns. But my question is how can I delete it after, as If i try to delete it in the main function, after i use it, it says it's undefined. Aren't dynamic arrays without a scope or I'm wrong?
Here's my code:
#include <iostream>
#include <string.h>
using namespace std;
bool areTheSame(const char * str, const char * what, unsigned p)
{
return areEqual;
}
unsigned howManyTimes(const char * str, const char * what)
{
}
char * stringReplace(const char * str, const char * what, const char * with)
{
}
int main()
{
char str[1000];
char what[1000];
char with[1000];
cout << "Enter your string\n";
cin.getline(str, 1000);
cout << "\nEnter \"what\" you want to replace\n";
cin.getline(what, 1000);
if (strlen(str) < strlen(what))
{
cout << "\"What\" contains more characters than the string!\n";
return 0;
}
cout << "\nEnter with what you want to replace it\n";
cin.getline(with, 1000);
cout << "\nYour string with replaced words looks like\n";
cout << stringReplace(str, what, with) << endl;
return 0;
}
P.S I deleted parts of the code as I found the answer I wanted and there is still time for the task, and I'm not sure I'm allowed to post my code publicly
You have to delete it in order to avoid memory leak. You can do something like this:
int main()
{
char str[1000];
char what[1000];
char with[1000];
char *replaced;
cout << "Enter your string\n";
cin.getline(str, 1000);
cout << "\nEnter \"what\" you want to replace\n";
cin.getline(what, 1000);
if (strlen(str) < strlen(what))
{
cout << "\"What\" contains more characters than the string!\n";
return 0;
}
cout << "\nEnter with what you want to replace it\n";
cin.getline(with, 1000);
cout << "\nYour string with replaced words looks like\n";
replaced = stringReplace(str, what, with);
cout << replaced << endl;
delete [] replaced;
return 0;
}
However note that this isn't the best pratice to split allocation/deallocation responsibility.
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();
Trying to learn C++ and came across OOP. I don
t grasp how strncpy(m_strName, strName, 25); works. Isn't this a function? Where is it calling from? I see that it is calling m_strName by pointing through *strName, but how are the values being passed here?
source: program tutorial
#include <iostream>
class Employee
{
public:
char m_strName[25];
int m_nID;
double m_dWage;
// Set the employee information
void SetInfo(char *strName, int nID, double dWage)
{
strncpy(m_strName, strName, 25);
m_nID = nID;
m_dWage = dWage;
}
// Print employee information to the screen
void Print()
{
using namespace std;
cout << "Name: " << m_strName << " Id: " <<
m_nID << " Wage: $" << m_dWage << endl;
}
};
int main()
{
// Declare two employees
Employee cAlex;
cAlex.SetInfo("Alex", 1, 25.00);
Employee cJoe;
cJoe.SetInfo("Joe", 2, 22.25);
// Print out the employee information
cAlex.Print();
cJoe.Print();
return 0;
}
char * strncpy ( char * destination, const char * source, size_t num )
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
strncpy(m_strName, strName, 25); will copy 25 characters from strName to m_strName. This function resides in the cstring header file. You will have to include this file in order to use this function.
If you understand this, you will realise that most of your questions don't make sense.
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.