This class takes in a name, job title, which are both stored in a char array, and age. An “Invalid conversion from ‘char *’ to ‘char’ occurs when I run the program. I believe I am using the char arrays incorrectly, but am unsure what the issue is. The program works perfectly when using strings. Can you explain what I am doing wrong and how to fix my code? Please also explain how the errors show me what is wrong.
Thank you in adavance.
Header file (emplyee.h)
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
/*No need for passing arguments into the functions since they can
* call the variables declared in the private access specifier. */
class Employee
{
private:
char Name[20], Jobtitle[30]; //Why not working ?
int Age;
public:
Employee(char, int, char);
char getname(); /*Could having the name of the function the same as the variables cause a problem ? Yes it will*/
int getage();
char getjobtitle();
};
#endif // EMPLOYEE_H
Source File (employee.cpp)
#include "employee.h"
Employee::Employee( char n[20], int a, char j[30] )
{
Name = n; Age = a; Jobtitle = j;
}
char Employee::getname()
{
return(Name);
}
int Employee::getage()
{
return(Age);
}
char Employee::getjobtitle()
{
return(Jobtitle);
}
Error messages print screen
Avoid char arrays (in most situations i.e. -03 is not good enough for what you want)
Use std::string. This is how it would look like.
Employee.h:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
class Employee{
private:
std::string Name, JobTitle;
int Age;
public:
Employee(std::string Name, int age, std::string JobTitle);
std::string getName();
int getAge();
std::string getJobTitle();
};
#endif
Employee.cpp
#include "employee.h"
#include <string>
Employee::Employee(std::string n, int a, std::string j){
Name = n;
Age = a;
JobTitle = j;
}
std::string Employee::getName(){
return Name;
}
int Employee::getAge(){
return Age;
}
std::string Employee::getJobTitle(){
return JobTitle;
}
main.cpp:
#include "employee.h"
#include <iostream>
int main(){
Employee e("Hemil", 16, "NA");
std::cout << e.getName() << "\n"
<< e.getAge() << "\n"
<< e.getJobTitle() << "\n";
}
Note: This will not work in Turbo C++
char getname();
means you are gonna return one char which is not correct because
char Name[20]
is a char array so you may want return the pointer to that array (which is of type char*) so your prototype should be
char* getname();
same goes for title
enter code here
Name and Jobtitle are arrays of char's you should use
strcpy(Name, n); and
strcpy(Jobtitle, j);.
Your getname and gettitle functions should be written as:
char *Employee::getname()
char *Employee::getjobtitle().
Related
I am new to c++ & don't know the basics all that well. pls help (sorry if the solution to this is already available, but I couldn't find any)
This is the Error I am getting:
expected primary-expression before ‘]’ token
char CusName[50]=x[];
^
For this code below:
#include <iostream>
using namespace std;
class BankAccount
{
private:
char CusName[50];
char CusId[10];
float accBalance, dep, witd;
public:
void setCusDetails(char x[], char n)
{
char CusName[50]=x[];
}
};
int main()
{
BankAccount customer1;
char cus1Name[50];
cin>>cus1Name;
customer1.setCusDetails(cus1Name, 50);
return 0;
}
Your char array looks like a string. Try using std::string instead and prefer using const references for function parameters.
If you want to use char arrays, and if your point was to copy a null-terminated string by value, then use functions like strncpy.
Using std::string may be easier for you to hide the burden of memory allocation and discover the language step by step.
You can instead use string to input and pass values.
#include <iostream>
using namespace std;
class BankAccount
{
private:
string CusName; //CusName of type string
char CusId[10];
float accBalance, dep, witd;
public:
void setCusDetails(string str, char n) //parameter str of type string
{
CusName=str; //Assign it to the already declared 'CusName' variable.
}
};
int main()
{
BankAccount customer1;
string cus1Name;
cin>>cus1Name;
customer1.setCusDetails(cus1Name, 50);
return 0;
}
This line canot pass under VS Studio, But it is running under CodeBlocks.
cg1.RegisterGoods("c++", 23, 32);
'void CGoods::RegisterGoods(char [],int,float)': cannot convert argument 1 from 'const char [4]' to 'char []'
like so:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <cstring>
using namespace std;
class CGoods
{
private:
char Name[21];
int Amount;
float Price;
float Total_value;
public:
void RegisterGoods(char name[], int amount, float price)
{
strcpy(Name,name);
Amount = amount;
Price = price;
}
void CountTotal(void)
{
Total_value = Price * Amount;
}
void GetName(char name[])
{
strcpy(name,Name);
}
int GetMount(void)
{
return Amount;
}
float GetPrice(void)
{
return Price;
}
float GetTotal(void)
{
return Total_value;
}
};
int main() {
CGoods cg1;
cg1.RegisterGoods("c++", 23, 32);
cout<<cg1.GetPrice()<<endl;
cout<<cg1.GetMount();
return 0;
}
char name[] as a function parameter is equivalent to char *name while your string literal has a type const char [4] which can only be (safely) converted to const char *, so you have to change your parameter like this:
void RegisterGoods(const char *name, int amount, float price)
and here:
// Renamed to SetName given that it's what this function actually does
void SetName(const char *name)
In general though you shouldn't use plain char arrays to store strings in C++, you should instead prefer using std::string:
std::string Name;
...
void SetName(std::string name)
{
// take advantage of move semantics to avoid redundant copying
// if you are using C++11 and beyond
Name = std::move(name);
}
Don't use c-constructs for things, c++ has better answers. char-pointers can lead to unwanted behaviors and nasty buffer overflow exploits and so on. It is far better to use a std::string.
Change your member-function RegisterGoods to:
void RegisterGoods(std::string const & name, int const amount, float const price)
{
Name = name;
Amount = amount;
Price = price;
}
and your declaration of Nameto:
private:
std::string Name;
your return function GetName to:
std::string GetName() const
{
return Name;
}
OR
void GetName(std::string & name) const
{
name = Name;
}
also add the include for std::string:
#include <string>
Tip for a better code... don't use using namespace std. std is a enormously huge namespace. Unintentionally you may override a function out of std and you end up with a nearly undebuggable error.
Also define your parameters in setter functions as const, so you can't change the value of it unintentionally.
Is that means that we don't need strcpy and char in c++ anymore? Because i replaced all the 'char' with string and its funktion also. like this:
private:
std::string Name;
public:
void RegisterGoods(const string name, int amount, float price)
{
Name=name;
Amount = amount;
Price = price;
}
const std::string GetName()
{
return Name;
}
OK here is my code. I have struct named employee and it has a member char* name. How do I change the value of name?
struct employee {
char* name;
int age;
};
int main()
{
struct employee james;
james.age=12; // this line is fine
james.name = "james"; // this line is not working
cout << james.name;
return 0;
}
Use std::string instead of char* pointer, it will work fine
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
Or
If you want to use char* pointer then use const char* name it will work.
#include <iostream>
struct employee {
const char* name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
Any literal string value you enter into your source code (such as "james") is by definition a const char* value, the const meaning it may not be altered at program runtime. In your class the name member is declared to be of type char* which is not const and so may be altered at runtime. Your compiler does not allow you to assign a const char* value to a variable of type char* to maintain the invariant that a value of type const char* may not be modified. (The other way around is fine of course; you may assign a char* value to a variable of type const char*.
To fix this with the fewest characters, you must change char* name to const char* name in your employee struct definition. However, I agree that the best thing to do is change it to a std::string member as #Hamza.S laid out in their answer. The std::string class has an assignment operator that builds it out of a const char* value, so the line james.name = "james" in their answer essentially sets the std::string equal to the const char* value "james".
If you are keen on using char*, you could do something like this :
#include <iostream>
#include <string.h>
#include <stdlib.h>
struct employee {
char *name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = (char *)malloc(sizeof(char) * 10);
strcpy(james.name, "James");
std::cout << james.name << std::endl;
return 0;
}
Or else you could use std::string in your struct like this :
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
You can try using strcpy
strcpy(james.name, "james");
I have a class BankAccount with two string members - name and num. What I want is to assign values to these objects when I create them (when the constructor is called). However the compiler says No instance of constructor matches the argument list when I try to create an object.
I would like to ask why is that?
// hwk-2.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class BankAccout {
char name[23];
char num[15];
double sum;
public:
BankAccout(char *nm, char *nr, double s) {
strcpy(name,nm);
strcpy(num, nr);
sum = s;
}
};
int main()
{
BankAccout k("Peter", "0403940940", 34.21);
}
as a coffee break exercise here is more idiomatic version
#include "pch.h"
#include <iostream>
#include <string>
class BankAccount {
std::string name_;
std::string num_;
double sum_;
public:
BankAccount(std::string name, std::string num, double sum) {
name_ = name;
num_ = num;
sum_ = sum;
}
};
int main()
{
BankAccount k("Peter", "0403940940", 34.21);
}
The signature of the constructor does not match.
This one will match:
BankAccount(const char *nm, const char *nr, double s);
EDIT:
The reason is the way you are calling the constructor in the main function. You are giving literal strings as parameters. These literals are const, you cannot change them at runtime. Thus you will pass pointers to const char*.
This is very obvious if you look at this opposing example. This is a way that would be compatible with the old signature BankAccout(char *nm, char *nr, double s);.
int main(int argc, char* argv[])
{
char name[] = "hello";
char number[] = "1234";
std::cout << "name before: " << name << std::endl;
BankAccount k(name, number, 8.5);
// name and number are not const,
// you can change them :
name[2] = 'x';
name[3] = 'x';
std::cout << "name after: " << name << std::endl;
return 0;
}
An even simpler version, if you don’t need to have additional functionality in the class: just use a struct.
#include <string>
struct BankAccount {
std::string name;
std::string number;
double balance;
};
int main() {
BankAccount account{"Joy", "44", 43.};
}
I am trying to print out a C string that is stored in a class by returning the value using an accessor function.
Thanks for any help!
This is the error I get when I compile:
cstringClass.cpp: In member function 'char Foo::get_name()':
cstringClass.cpp:37:9: error: invalid conversion from 'char*' to 'char' [-fpermi
ssive]
return name;
^
Here is the code:
#include <iostream>
#include <cstring>
using namespace std;
class Foo
{
public:
void set_name(char a[]);
char get_name();
private:
char name[10];
};
int main()
{
Foo bar;
char a[10] = "Test";
bar.set_name(a);
cout << bar.get_name();
return 0;
}
void Foo::set_name(char a[])
{
strcpy(name, a);
}
char Foo::get_name()
{
return name;
}
So the error says:
cstringClass.cpp: In member function 'char Foo::get_name()':
^^^^^^^^^^^^^^^^^^^^
And indeed:
char get_name();
You declared get_name as returning a single char, not a pointer to a string. You probably meant char *get_name();.
As the error message states, your get_name() function doesn't return the appropriate type, which should be char* based on the data it returns, which is name[10]. char returns only 1 byte of data and name[10] has 10. Please see the corrected code below.
#include <iostream>
#include <cstring>
using namespace std;
class Foo
{
public:
void set_name(char a[]);
char *get_name(); //<-- correction
private:
char name[10];
};
int main()
{
Foo bar;
char a[10] = "Test";
bar.set_name(a);
cout << bar.get_name();
return 0;
}
void Foo::set_name(char a[])
{
strcpy(name, a);
}
char *Foo::get_name() //<-- correction
{
return name;
}