errror: invalid conversion from 'const char*' to 'int' - c++

I am trying to add to a class a person's day, month and year of birth. As of now, i am at trying to include the day of birth, had lots of errors, managed to get rid of most of them but i still have this one left(at first, i included at the same time the day, month and year of birth but i had many erros so i decided to try and fix at least one of them). In the code i also have the birth date as a char and that works fine but i need those values to work with them later.
#include <iostream>
#include <cstring>
using namespace std;
class Persoana
{
private:
char nume[20];
char data_nastere[20];
int zi;
public:
Persoana(char *nume="", char *data_nastere="", int zi="");//this is where i have the error
void setNume(char *nume);
char* getNume();
void setDataNastere(char *data_nastere);
char* getDataNastere();
void setZi(int zi);
int getZi();
void afisare();
};
Persoana::Persoana(char *nume, char *data_nastere, int zi)
{
setNume(nume);
setDataNastere(data_nastere);
setZi(zi);
}
void Persoana::setNume(char *nume)
{
strcpy(this->nume, nume);
}
char* Persoana::getNume()
{
return nume;
}
void Persoana::setDataNastere(char *data_nastere)
{
strcpy(this->data_nastere, data_nastere);
}
char* Persoana::getDataNastere()
{
return data_nastere;
}
void Persoana::setZi(int zi)
{
this->zi=zi;
}
int Persoana::getZi()
{
return zi;
}
void Persoana::afisare()
{
cout<<"Nume: "<<nume<<endl;
cout<<"Data nasterii este: "<<data_nastere<<endl<<endl;
cout<<zi<<endl;
}
int main()
{
Persoana p[] = {Persoana("Calin Dorina", "12 02 2000", 12), Persoana("Mihaela Banu", "25 04 2001", 25)};
p[0].afisare();
//p[1].afisare();
}

You try to assign a pointer to literal string (it's pointer to const char which is fist letter in this string) to the integer property z in constructor: int zi="". C++ hasn't default conversion from const char* to int. You should use integer default values for integer properties.

One of you said to declare int zi=0 and thats the right answer. I tried doing it before but where i declared the private variables. Thanks for helping!
In case someone else has this problem, here it is how its supposed to be:
Persoana(char *nume="", char *data_nastere="", int zi=0);

Related

Nothing prints; do I need a main or should it work without it, theoretically?

I'd hate to ask this but I've been trying this for HOURS and I can't figure it out. I'm brand new to C++ and can't figure out why the sprintf_s won't put anything out at the end (or both of them for that matter). Basically, nothing happens in Visual Studio 2019 except the window pops up. I know it's a simple solution but I am going crazy trying to figure it out. Also, do I HAVE to have a main or should it work without it? Ok, also, does my constructor look ok? I have the green squiggly under it and not sure how to fix it or if I can ignore that. I appreciate all the help I can get! Thank you!
//#include "stdafx.h" - commented out as I think this version of VS does
//this automatically (I looked under precompiled headers and it was listed as "Precompiled Header File"
//and it wouldn't work unless I commented it out
#include <iostream>
using namespace std;
// Base Entree class
class Entree
{
protected:
char _entree[10];
public:
const char* getEntree()
{
return _entree;
}
};
// Base Side class
class Side
{
protected:
char _side[10];
public:
char* getSide()
{
return _side;
}
};
class Drink
{
protected:
char _drink[10];
public:
Drink()
{
cout << "\n Fill cup with soda" << endl;
strcpy_s(_drink, "soda");
}
char* getDrink()
{
return _drink;
}
};
// ADDED CODE:
class ComboMeal
{
private:
Entree* entree;
Side* side;
Drink* drink;
char _bag[100];
public:
ComboMeal(const char* type)
{
sprintf_s(_bag, "/n %s meal combo: ", type);
}
void setEntree(Entree * e)
{
entree = e;
}
void setSide(Side * s)
{
side = s;
}
void setDrink(Drink * d)
{
drink = d;
}
const char* openMealBag()
{
sprintf_s(_bag, "%s, %s, %s, %s", _bag, entree->getEntree(), side->getSide(), drink->getDrink());
return _bag;
}
};
int main()
{
}
As it's been said in the comments, in C++ the code that's executed is the one in the main function. Constructors are called when objects of the correspondent class are created, so you should at least have something like this:
int main(){
ComboMeal combo("my type one");
return 0;
}
A more complete example would be:
int main(){
ComboMeal combo("my type one");
combo.setEntree(new Entree);
combo.setSide(new Side);
combo.setDrink(new Drink);
cout << combo.openMealBag() << endl;
return 0;
}
(Of course this will print garbage, because the values within the new objects are not set)

oop in c++ (password generation)

Object oriented programming in c++
I am learning oop in c++ and cannot use oop for this problem. oop might not be the best solution for this
but I want in it. This question might be simple but i could not solve this it shows
**error: cannot convert '<brace-enclosed initializer list>' to 'char' in assignment**
#include <iostream>
#include<ctype.h>
#include<time.h>
#include<stdlib.h>
#include<string>
#include<string.h>
#include<ctime>
using namespace std;
class passwordGenerate{
private:
char letters[56];
int length;
char password[100];
public:
passwordGenerate();
void setLength(int);
void setPassword(char p[]);
void displayPassword();
};
passwordGenerate::passwordGenerate(){
letters[56] = {'a','b','c','d','e',
'f','g','h','i','j',
'k','l','m','n','o',
'p','q','r','s','t',
'u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9',
'.','+','-','*','/',
'=','_',')','(','&',
'%','$','#','#','!',
'~',',','>','?','<'};
//it works when char letters[56] is given but does not work in this way.
}
void passwordGenerate::setLength(int l){
length = l;
}
void passwordGenerate::displayPassword(){
strcpy(password," ");
int random;
srand(time(0));
for(int x =0 ;x<length;x++){
random = rand()%55;
password[x] = letters[random];
}
for(int i=0;i<length;i++){
cout<<password[i];
}
}
int main()
{
passwordGenerate firstPassword;
int length;
cout<<"enter the length for password : ";
cin>>length;
firstPassword.setLength(length);
firstPassword.displayPassword();
return 0;
}
There is a fundamental difference between [] in those two
int x[5] = {1,2,3,4,5};
// ^----------------- size of the array
x[2] = 42;
//^--------------------- index of array element
So when you write
letters[56] = {'a',' .....
Then this is first accessing the array out of bounds (it has 56 elements and letters[56] is the 57-th). And you cannot assign {'a',... to a single char (type of elements).
To fix the problem I suggest you to work with std::string instead and use in-class initializer:
struct foo {
std::string letters{"abcdefghijklmnop...."};
};
Last but not least, I would suggest to name that member alphabet rather than letters, because it is not only letters.

How to debug a C++ program using arrays?

#include<iostream.h>
#include<conio.h>
class XIIB
{
char name[30];
int age;
int roll;
float marks;
public:
void getdata(char a[30],int i,int j,float k)
{
name[30]=a[30];
age=i;
roll=j;
marks=k;
}
void putdata(void)
{
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age<<endl;
cout<<"Roll:"<<roll<<endl;
cout<<"Marks:"<<marks<<endl;
}
};
const int size=5;
XIIB student[size];
void main()
{
char x[30];
int ag;
int rno;
float mrks;
for(int p=0;p<size;p++)
{
cout<<"Enter Name,Age,Roll and Marks of Student"<<p+1<<endl;
cin>>x>>ag>>rno>>mrks;
student[p].getdata(x,ag,rno,mrks);
}
for(p=0;p<size;p++)
{
cout<<"Student"<<p+1<<endl;
student[p].putdata();
}
getch();
}
This program compiles without any error. Also takes the input for Name, Roll No, Age and Marks as expected but it is unable to display the name of the Students. I seem to have made some error in the getdata or putdata functions.
In void getdata(char a[30],int i,int j,float k): name[30]=a[30]; does not make what you expect and is undefined behavior; (this copies the 31st character of a to the 31st character of name, while both strings are only 30 characters long.)
You have to replace name[30]=a[30]; by strcpy(name,a); and this should work.
your getdata has a problem, character arrays cannot be copied like that, try this
void getdata(char a[30],int i,int j,float k)
{
strcpy(name,a); //change this line
age=i;
roll=j;
marks=k;
}
instead of
name[30]=a[30];

c++ method parameters giving unexpected output

Main class code:
#include <iostream>
#include "Chair.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
Chair c1;
c1.chairType("Olivia",4,32,true); // not working
Chair c2;
c1.chairType("Stephano",8,8,false);
return 0;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Header class code:
#ifndef CHAIR_H_INCLUDED
#define CHAIR_H_INCLUDED
#include <iostream>
using namespace std;
class Chair
{
private:
int legCount;
int height;
bool cushioned;
string name;
public:
void chairType(string newName, int newLegCount, int newHeight, bool cush);
};
#endif // CHAIR_H_INCLUDED
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Chair.cpp class:
#include <iostream>
#include "Chair.h"
using namespace std;
void Chair::chairType(string newName, int newLegCount, int newHeight, bool cush)
{
name=newName;
legCount=newLegCount;
newHeight=newHeight;
cushioned=cush;
cout<<"I'm a chair, the following are my specs: "<<endl;
cout<<"Model: "<<name<<endl;
cout<<"Num of Legs: "<<legCount<<endl;
cout<<"Height: "<<height<<endl;
cout<<"Cushioned? : "<<cush<<endl;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output for the four variables fed into the method is as expected, apart from the third variable (second int) which is printing as being 2752192 regardless of what I feed to it, and for both objects c1 and c2.
I'm new to C++. I've been practising some object class questions trying to familiarise myself with the syntax. I vaguely understand pointers can cause reference addresses to print on occasion. However, this 7 digit number doesn't appear to be in address format. I've done some searches and can't see a similar question. If there is one, I would appreciate direction to it. I don't wish to break the terms of posting here on the site. Thank you in advance for your assistance.
newHeight=newHeight;
should be replaced with
height=newHeight;
but better you should initialize object in constructor, rather than separate method:
class Chair
{
private:
int legCount;
int height;
bool cushioned;
string name;
public:
Chair( const string &newName, int newLegCount, int newHeight, bool cush) :
legCount( newLegCount ),
height( newHeight ),
cushioned( cush ),
name( newName )
{
}
...
};
int main()
{
cout << "Hello world!" << endl;
Chair c1("Olivia",4,32,true); // works now
Chair c2("Stephano",8,8,false);
return 0;
}
this way you cannot have instance of your class uninitialized and your mistake also would be detected by compiler.
Here is the mistake in your implementation Chair.cpp:
newHeight=newHeight;
This is the correct:
height = newHeight;
The long number you get is the uninitialized value of member variable height in your Chair object.

C++ binary file with records: string at beginning

I am struggeling with reading from a binary file.
My binary file is made of records in the way like:
string - 5 x integers
The first string has differenct lengths, so I guess this may be my problem?
I try to read a record into a class which has the same type of attributes:
class Team
{
private:
string teamName;
int matchesPlayed;
int gamesWon;
int gamesLost;
int pointsWon;
int pointsLost;
public:
Team(string ="",int = 0,int = 0, int = 0, int = 0, int = 0);
~Team();
//void operator<();
void setTeamName(string);
void setMatchesPlayed(int);
void setGamesWon(int);
void setGamesLost(int);
void setPointsLost(int);
void setPointsWon(int);
void print();
};
I try to read in from another class:
Table::Table()
{
Team t1;
teams.push_back(t1);
ifstream inputFile;
inputFile.open("tabletennis.dta", ios::in | ios::binary);
if(!inputFile)
{
cout << "Datei konnte nicht geoeffnet werden!";
exit(1);
}
if(inputFile.good())
inputFile.read(reinterpret_cast<char*> (&t1), sizeof(Team));
t1.print();
}
Team::print() just prints out the content of its attributes. But the program crashes when I try to print the string.
I don't know what I may understood wrong.. but what I thought was:
Reading in to an Object with the same count and type of attributes is they way how to read a record set:
Team::Team(string teamName, int matchesPlayed, int gamesWon, int gamesLost, int pointsWon, int pointsLost)
{
setTeamName(teamName);
setMatchesPlayed(matchesPlayed);
setGamesWon(gamesWon);
setGamesLost(gamesLost);
setPointsWon(pointsWon);
setPointsLost(pointsLost);
}
Don't know for now..
Yep, if you want to do record-based I/O, then the records must really all have the same length. and record-based I/O is a rare occasion when using an array of char may be a better bet than a std::string. I would change this:
class Team
{
private:
string teamName;
int matchesPlayed;
int gamesWon;
int gamesLost;
int pointsWon;
int pointsLost;
to:
class Team
{
private:
char teamName[NAMESIZE];
int matchesPlayed;
int gamesWon;
int gamesLost;
int pointsWon;
int pointsLost;
You can then read and write:
Team t( .... ); // construct a team
os.write( (const char *) & t, sizeof( t ) );
and read:
Team t; // default construct empty team
is.read( (char *) & t, sizeof( t ) );
Nothing more to add to the answer of Neil but
I would suggest that you take a look at boost serialization.
If your file format is not fixed and you can easily change it, this will really help you to avoid a lot of traps in serialization.