Consider the following constructor of a class i C++. It gives me the error :
default argument for parameter of type ‘char’ has type ‘const char [2]’
Some advices please. I would be happy if I could set the default constructor for correctAnswer at "" (nothing).
#include <string>
#include <iostream>
class Question{
int id;
std::string text;
char correctAnswer;
public:
Question(int id=0, const std::string& text="", char correctAnswer="a") : // here is the error
id(id),text(text),correctAnswer(correctAnswer) {
}
}
Change it to
Question(int id=0, const std::string& text="",char correctAnswer='a')
'a' is a single char.
Double quotes always creates an array.
"Hello" is an array of size 6.
"a" is an array of size 2.
The extra 1 is for a null terminator (0 or '\0')
Question(int id=0, const std::string& text="",
char correctAnswer='a')
// ^^ Use single Quote for a char
id(id),text(text),correctAnswer(correctAnswer)
{
}
Related
My code in VS2019 is not working.
In the last line of code compiler throws an error.
#include <iostream>
#include <string>
using namespace std;
struct struct1
{
string name;
};
void main()
{
struct1* obj1 = new struct1();
obj1->name = "Hello";
// compiler says 'initializing': cannot convert from 'const _Elem *' to 'char [25]'
char str[25] = (obj1->name).c_str();
}
c_str() returns a pointer to the start of the string's character data. You'll need to copy the characters into your array using something like strncpy().
there is a lot of ways to do this
but first you should change the manner of char array initialization because you made it wrongly.
this is the same program but working
#include <iostream>
using namespace std;
struct struct1
{
string name;
};
int main()
{
struct1* obj1 = new struct1();
obj1->name = "Hello";
char str[25] = "";
memcpy(&str,obj1->name.c_str(),obj1->name.size());
cout << str << endl;
}
#include <iostream>
#include <string.h>
using namespace std;
void ArrayTimesThree(char*, const char*);
int main()
{
char s1[200], s2[200], circleword[200];
cin.getline(s1, 200);
cin.getline(s2, 200);
ArrayTimesThree(circleword, s1);
cout<<circleword[1];
}
void ArrayTimesThree(char *dest[], char *source[])
{
*dest[0] = NULL;
strcat(*dest, *source);
strcat(*dest, *source);
strcat(*dest, *source);
}
main.cpp|21|error: cannot convert 'char (*)[200]' to 'char**' for argument '1' to 'void ArrayTimesThree(char**, char**)'
You're passing ArrayTimesThree a char*, however, in the method signature you're telling it to expect a char**. Don't forget that that using the [] operator counts as a dereference. Try this:
#include <iostream>
#include <string.h>
using namespace std;
void ArrayTimesThree(char*, char*);
int main()
{
char s1[200], s2[200], circleword[200];
cin.getline(s1, 200);
cin.getline(s2, 200);
ArrayTimesThree(circleword, s1);
cout<<circleword[1];
return 0;
}
void ArrayTimesThree(char *dest, char source[])
{
dest[0] = '\0';
strcat(dest, source);
strcat(dest, source);
strcat(dest, source);
}
Disclaimer: I'm not sure what exactly you're expecting out of this code, so I cannot guarantee the logic is correct; however, this will take care of your compiler errors and seems to function correctly for how the code is written.
The problem is really just because your initial declaration of ArrayTimesThree (which is the 'correct' one) doesn't match the definition you later give (which is wrong, in fact). Change your definition as below and it works:
void ArrayTimesThree(char* dest, const char* source) // Needs to be the same as in the previous declaration!
{
dest[0] = '\0'; // Don't assign a string pointer to NULL! Instead, set its first character to the nul character
// strcpy(dest, ""); // ALternatively, use strcpy with an empty string to clear "dest"
strcat(dest, source); // strcat takes char* and const char* arguments ...
strcat(dest, source); // ... so there is no need to 'deference the values ...
strcat(dest, source); // ... now that the argument types have been 'corrected'
}
Incidentally, I notice that the input value for s2 in your main function is never actually used … is this what you intend, for now?
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().
I am trying this simple piece of code to accept a string in one function and pass it to other function
#include <iostream>
#include <string>
using namespace std;
void set_name(char *deviceName)
{
cout<<"Local Device name is:"<<endl;
cout<<deviceName<<endl;
}
void enter_name()
{
cout<<"Enter a user friendly name"<<endl;
string name;
getline(cin, name);
cout << "Entered name is:"<<endl;
cout << name<<endl;
set_name(name);
}
int main()
{
enter_name();
return 0;
}
but when I compile this code I am getting the following errors:
error C2664: 'set_name' : cannot convert parameter 1 from 'std::string' to 'char *'
somebody please help me to sort out this error, make sure I don't want to change the prototype of set_name();
Your function set_name is taking a char* parameter, whereas you are attempting to pass a std::string. If your function parameter was a const char*, it would implicitly convert for you:
void set_name(const char* name);
std::string name = "MyName";
set_name(name);
However, you are telling the compiler that this char* is allowed to be modified because it isn't const, and a std::string and string literal (strings within double-quotes) cannot be modified.
As your function does not change deviceName, it makes the most sense to make your parameter a const char*; however, it makes even more sense for it to be a std::string!
void set_name(const std::string& deviceName)
{
cout<<"Local Device name is:"<<endl;
cout<<deviceName<<endl;
}
Which can be called like:
// string literal
set_name("MyDeviceName");
const std::string device = "MyDeviceName";
// string
set_name(device);
// char*
char* device = "MyDeviceName"
set_name(device);
BUT, if you truly have reasons to pass a char* and don't intend to modify the parameter, you can call it like so:
string name;
...
set_name(&name[0]);
So I have a class, Mail, with a class data member, char type[30]; and static const char FIRST_CLASS[]; outside of the class definition i initialize FIRST_CLASS[] to "First Class".
In my default Mail constructor I would like to set type to FIRST_CLASS[] but cannot seem to figure out a way to do so. Here's the code (a bit stripped down so not to bother you with stuff you dont need)
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
using namespace std;
class Mail
{
public:
Mail();
Mail(const char* type, double perOunceCost, int weight);
Mail(const Mail& other);
~Mail()
{ }
private:
static const int TYPE_SIZE = 30;
static const char FIRST_CLASS[];
static const double FIXED_COST;
static const int DEFAULT_WEIGHT = 1;
char type[TYPE_SIZE];
int weight;
double perOunceCost;
};
const char Mail::FIRST_CLASS[] = "First Class";
const double Mail::FIXED_COST = 0.49;
// default
Mail::Mail()
{
weight = DEFAULT_WEIGHT;
perOunceCost = FIXED_COST;
type = FIRST_CLASS;
}
and here's the errors:
1 error C2440: '=' : cannot convert from 'const char [12]' to 'char [30]'
2 IntelliSense: expression must be a modifiable lvalue
You can not assign one array to another. try strcpy
strcpy(type,FIRST_CLASS);
Make sure destination is at least as large as source.
Note: If not mandatory, you should avoid array and use std::string for character array, and other STL containers (vector,map.. etc.).
The error you are getting is not because you're trying to assign a const char array to a char array (yet - it will be an error). The error you're reporting is because you're trying to assign an array of size 12 ("First Class" is 12 characters long) to an array of size 30. You would get the same error even if both arrays were const, or non-const.
Since this is C++ and not C, like others have suggested, you should use std::string. Here is your example using std::string instead of char arrays.
#include <string>
using namespace std;
class Mail
{
public:
Mail();
Mail(string type_, double perOunceCost_, int weight_);
private:
static const int TYPE_SIZE = 30;
static const string FIRST_CLASS;
static const double FIXED_COST;
static const int DEFAULT_WEIGHT = 1;
string type;
int weight;
double perOunceCost;
};
const string Mail::FIRST_CLASS("First Class");
const double Mail::FIXED_COST = 0.49;
// default
Mail::Mail()
{
weight = DEFAULT_WEIGHT;
perOunceCost = FIXED_COST;
type = FIRST_CLASS;
}
Mail::Mail(string type_, double perOunceCost_, int weight_) :
type(move(type_)),
weight(weight_),
perOunceCost(perOunceCost_)
{}