Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a value of type "const char *" cannot be assigned to an entity of type "char" C OOP

Tags:

c++

oop

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
};
like image 592
Luke Avatar asked Nov 29 '13 22:11

Luke


2 Answers

C++ has two types of constants consisting of characters - string literals and character literals.

  • String literals are enclosed in double quotes, and have type of const char *
  • Character literals are enclosed in single quotes, and have type 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';
like image 78
Sergey Kalinichenko Avatar answered Oct 25 '22 08:10

Sergey Kalinichenko


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';
like image 20
kfsone Avatar answered Oct 25 '22 06:10

kfsone