Comparing Input with characters

Hi, I'm a beginner trying to learn C++. I'm trying to do a simple calculator.
I need the player to type the operation he needs to do. ex: multiply, addition, etc. And if player typed in "multiply" I need to check if its "multiply" compare characters. And I hope you'll understand it better if looked at the code.

Thanks in ADVANCE!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int n1;
int n2;
char operation;

int main ()
{
    cout << "What is the operation? ex: multiply, addition, etc\n";
    cin >> operation;
    cin.ignore();
    if(operation == "multiply") {
        cout << "Insert number you want to Multiply?\n";
        cin >> n1;
        cin.ignore();
        cout << "From?\n";
        cin >> n1;
        cin.ignore();
        cout << "Answer is : " << n1 + n2 << "\n";
    }
}
Last edited on
"multiply" is not a single character; it is a string (a sequence of characters).
We use std::string for this. http://www.mochima.com/tutorials/strings.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

int main()
{
    std::cout << "What is the operation? ex: multiply, addition, etc\n";
    std::string operation ;
    std::cin >> operation;

    if( operation == "multiply" ) {

        std::cout << "What do you want to multiply?\n";
        int n1 ;
        std::cin >> n1;

        std::cout << "With?\n";
        int n2 ;
        std::cin >> n2;

        std::cout << "Answer is : " << n1 * n2 << '\n' ;
    }
}


Alternatively, we can represent an operation by a single character '+', '*' etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
    std::cout << "What is the operation? ex: *, +, etc\n";
    char operation ;
    std::cin >> operation;

    if( operation == '*' ) {

        std::cout << "What do you want to multiply?\n";
        int n1 ;
        std::cin >> n1;

        std::cout << "With?\n";
        int n2 ;
        std::cin >> n2;

        std::cout << "Answer is : " << n1 * n2 << '\n' ;
    }
}
Last edited on
Wow thanks! And why are those "std::cin...", "std::cout" used for? I mean the "std" part, what is it for? And I need to loop the program again, like when one operation is complete it again displays "What is the Operation"...

Thanks again!
> And why are those "std::cin...", "std::cout" used for? I mean the "std" part, what is it for?

See: http://www.cplusplus.com/forum/beginner/142171/#msg750694


> And I need to loop the program again, like when one operation is complete it again displays "What is the Operation"...

Something along these lines:
1
2
3
4
5
6
7
8
9
char y_or_n ;
do
{
     // displays "What is the Operation"
     // etc.

     std::cout << "once again (y/n)? " ;
     std::cin >> y_or_n ;
}while( y_or_n  == 'y' ) ;
Yup! Works!

Thanks!
Topic archived. No new replies allowed.