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
};
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';
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With