How to call a function with parameters and user console input in C++?

This is C++ console snippet.

I wish to call a fonction holding parameters amongst several function depending on user input.

For example:

#include<iostream>
using namespace std;

void Add (int x, int y)
    {
        cout << x + y << endl;
    }

void Subs (int x, int y)
    {
        cout << x - y << endl;
    }


int main(int argc, char* argv[])
{
    // Variable initialization
    char calc_type;
    int x;
    int y;

    // Console input
    cout << "Add or Substract (a or s)?" << endl;
    cin >> calc_type;
    cout << "1st number" << endl;
    cin >> x;
    cout << "2nd number" << endl;
    inc >> y;

    if (calc_type == "a")
    {
        Add(x, y);
    }
    else
    {
        Subs(x, y);
    }

return 0;

}

But in writing this I am returned error messages like the followings:

error C2446: '==' : no conversion from 'const char *' to 'int'

There is no context in which this conversion is possible

error C2040: '==' : 'int' differs in levels of indirection from 'const char [2]'

How can I cope with this problem (maybe references or pointers are preferred???)

Thank you

Answers


calc_type is a char variable. The constant "a" is a string. In C, char constants are in single quotes, not in double ones. So rephrase as:

if (calc_type == 'a') 

Use single quotation marks for character literals.

if (calc_type == "a")

The double quotation marks here mean that "a" is a string literal, which means it has the type const char[2] ({'a', '\0'}). calc_type is a char, so the types don't match. 'a', on the other hand, has a character type, which you can compare fine.


Perhaps you meant:

calc_type == 'a'

instead of

calc_type == "a"

since calc_type is a char and "a" is a const char*?


Need Your Help

What SQL better for calculated members age? (MySQL MYISAM)

mysql sql

I'm trying to show my members age in profile page.

Using CreateFile to check exclusive write access

c++ windows winapi createfile

I need to check for exclusive write access of a file. I put in this code.