c ++错误c2015:常量中的字符太多

时间:2014-09-11 15:21:15

标签: c++

很抱歉,如果这很简单,但我是C ++的新手并没有真正掌握它。我需要构建一个计算器,其唯一的命名变量是指针,这是我到目前为止,但我不断得到错误,我无法弄清楚为什么。但是,每个错误总是与我的if构造有关。

int main()
{
    //Creating variables

    //Values to perform operations on
    float *aptr = new(nothrow)float;
    float *bptr = new(nothrow)float;
    float *ansptr = new(nothrow)float;
    int *endptr = new(nothrow)int;
    char *operationptr = new(nothrow)char;

    cout << "Simple Operation Calculator" << endl; //Displays program name
    cout  << "Performs +, -, *, or / on any two real operands." << endl; //Describes nature of program to user

    *endptr = 1;
    while(*endptr = 1) //Creates a loop so that the user may perform as many operations as desired
    {
        //Prompts the user for the first operand
        cout << "First operand: " << endl;
        cin >> *aptr;

        //Prompts user for operator
        cout << "Operator(+,-,*,/): " << endl;
        cin >> *operationptr;

        //Prompts user for second operand
        cout << "Second operand: " << endl;
        cin >> *bptr;

        //Performs requested operation
        if(*operationptr == '+' || *operationptr == 'plus')
        {
            *ansptr = *aptr + *bptr;
        }
        else if(*operationptr == '-' || *operationptr == 'minus')
        {
            *ansptr = *aptr - *bptr;
        }
        else if(*operationptr == '*' || *operationptr ==  'times')
        {
            *ansptr = *aptr * *bptr;
        }
        else if(*operationptr == '/' || *operationptr == 'divided by')
        {
            if(*bptr = 0)
            {
                cout << "Cannot divide by zero. Terminating program." << endl;
                *endptr = 2;
                break;
            }
            *ansptr = *aptr / *bptr;
        }
        else
        {
            cout << "Invalid operand input. Terminating program." << endl;
            *endptr = 2;
            break;
        }

        //Displays results
        cout << *aptr << *operationptr << *bptr << " = " << *ansptr << endl;

        //Asks user if they wish to perform another operation. If so, they stay in loop. If not, then break from loop.
        cout << "Do you wish to perform another operation? (1 = yes, 2 = no)" << endl;
        cin >> *endptr;

        //If 1, loop repeats. If 2, program ends.
        if (*endptr == 2)
        {
            cout << "Thank you for using my program. Goodbye!" << endl;
        }
    } //end while loop

    return 0;

 }//end main function

2 个答案:

答案 0 :(得分:6)

有字符文字(带')和字符串文字(带")。字符文字有一个字符。字符串文字是字符数组。你不能写像'plus'这样的东西,因为它有多个字符(技术上你可以,但它是一个多字符文字,但不能去那里)。

尽管如此,这没有任何意义,因为operationptr指向一个char个对象。单个char不能包含整个单词plus

如果您希望能够接受plus作为输入,那么我建议您开始使用字符串。实际上,请使用std::string

作为旁注,您经常使用指针和动态分配。您还忘记delete使用new创建的对象 - 这是内存泄漏。我想你是来自一种使用new来创建所有对象的语言。在C ++中,这不是必需的(并且不是一个好习惯)。相反,你可以像这样声明对象:

float aptr;

无需取消引用此对象。您可以直接将aptr用作float

答案 1 :(得分:5)

'plus'

是一个字符常量,不能包含多个字符。

'+'很好,因为它是常量中的单个字符。

根据对此答案的评论,

如果编译器不期望'plus'

char可能没问题。