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");
Related
I am trying to assign a const std::string variable to std::string variable.But getting some memory related error. code is like below:
#include <iostream>
#include <string>
using namespace std;
std::string sender1;
std::string fun()
{
const std::string sender = "hi";
sender1.assign(sender);
}
int main()
{
fun();
cout<<sender1<<endl;
return 0;
}
You've forgotten a return in fun. If you change that function like this:
std::string fun()
{
const std::string sender = "hi";
sender1.assign(sender);
return sender;
}
then the code will compile and run fine.
I got the answer finally.
We need to declare a char * globally. Then using const_cast <char *> we can convert the constant string to char and assign it.
Example: in .h file:
char * abc;
in .cc file:
func()
{
const std::string cde = "Hello";
//now to use this constant string in another function,we use const cast and
//assign it to abc like below
abc = const_cast <char *>(cde.c_str());
}
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().
if I have a c++ class like:
class Student
{
public:
string name;
int assigned_number;
};
and I want to use either name or number but not both for each instance, is there a way to make this an Or type where only one of them is required?
If you are using C++17 or above, you can use std::variant from <variant>:
#include <iostream>
#include <variant> // For 'std::variant'
class Student
{
public:
std::variant<std::string, int> name_and_id;
};
int main() {
Student stud; // Create an instance of student
// Pass a string and print to the console...
stud.name_and_id = "Hello world!";
std::cout << std::get<std::string>(stud.name_and_id) << std::endl;
// Pass an integer and print to the console...
stud.name_and_id = 20;
std::cout << std::get<int>(stud.name_and_id) << std::endl;
}
std::variant is a new addition to C++17 and is intended to replace the unions from C and has exceptions in case of errors...
You can use union.
#include <string>
class Student
{
// Access specifier
public:
Student()
{
}
// Data Members
union
{
std::string name;
int assigned_number;
};
~Student()
{
}
};
int main()
{
Student test;
test.assigned_number = 10;
test.name = "10";
return 0;
}
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;
}