Reputation: 317
I am creating a class to calculate a grade for a user in C++ and I am coming across a simple yet annoying problem. I know what the errors means but I don't understand how to fix it and changing to a string actually fixes the issue but this is not what I want to do.
here is the error: const char *" cannot be assigned to an entity of type "char
Code
#include <string>
using namespace std;
class Gradecalc
{
public:
Gradecalc()
{
mark = 0;
}
int getmark()
{
return mark;
}
void setmark(int inmark)
{
mark = inmark;
}
void calcgrade()
{
if (mark >=70)
{
grade = "A"; //**ERROR IS HERE**
}
}
char getgrade()
{
return grade;
}
private:
int mark;
char grade; //VARIABLE IS DECLARED HERE
};
Upvotes: 11
Views: 85679
Reputation: 24269
C and C++ use double quotes to indicate "string literal", which is very different from a "character literal".
char
(which is signed) is a type capable of storing a character representation in the compiler's default character set. On a modern, Western PC, that means ASCII, which is a character set that requires 7-bits, plus one for sign. So, char
is generally an 8-bit value or byte.
A character literal is formed using single quotes, so 'A'
evaluates to ASCII code 65. ('A' == 65
).
On the other hand, "A"
causes the compiler to write char(65) + char(0) into a part of the output program and then evaluates the expression "A"
to the address of that sequence; thus it evaluates to a pointer to a char sequence, but they're in the program data itself so they are not modifiable, hence const char*
.
You want
grade = 'A';
Upvotes: 2
Reputation: 727077
C++ has two types of constants consisting of characters - string literals and character literals.
const char *
char
.String literals allow multiple characters; character literals allow only one character. The two types of literals are not compatible: you need to supply a variable or a constant of a compatible type for the left side of the assignment. Since you declared grade
as a char
, you need to change the code to use a character literal, like this:
grade ='A';
Upvotes: 20
Reputation: 9146
Grade
is a char
variable, "A"
is a const char*
type.
You cannot assign const char*
into char
varible.
double quote means const char*
, and single qoute means char.
to fix that, replace:
grade="A"
with
grade='A'.
Upvotes: 0
Reputation: 5355
Replace
grade = "A";
by
grade = 'A';
You can only assign char to char, you cannot assign string to single char, and that is what you are trying to do.
Upvotes: 0