Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C++
#include<iostream>

using namespace std;
class calc
{
    int a,b,c;
public:
    void add()
    {
        cout<<"Enter values";
        cin>>a>>b;
        c=a+b;
        cout<<c;
    }
    void mul()
    {
        cout<<"enter values";
        cin>>a>>b;
        c=a*b;
        cout<<c;
    }
};
int main()
{
    calc obj;
    char f[10];
    cout<<"Select from the option 1. add, 2. mul";
    cin>>f;
    if(f=="add")
        obj.add();
    else if(f=="mul")
        obj.mul();
    else
        cout<<"invalid choice";

        return(0);

}


What I have tried:

I have executed this program but when ever i input add or mul it shows invalid choice.
PS i am new to programming.

thanks in advance
Posted
Updated 5-Sep-16 8:22am
Comments
PeejayAdams 5-Sep-16 11:51am    
Don't take my word for it because I don't know C++ but I'd try "if (f.compare("add") == 0)" in place of "if(f == "add")"

You have a char array (f[10]). Comparing such arrays with a constant string requires using the C function strcmp.
When using
if(f=="add")

you are comparing two pointers which will never be identical.

In your case it would be better to use a std::string instead which supports comparing using the == operator or the string::compare - C++ Reference[^] function. Then use getline (string) - C++ Reference[^] to read the input into the string object.
 
Share this answer
 
Comments
Maciej Los 5-Sep-16 14:05pm    
Short And To The Point!
A5!
[no name] 5-Sep-16 20:37pm    
Agree with above.
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900