Mar 4, 2015 at 1:53pm UTC
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 Mar 4, 2015 at 1:54pm UTC
Mar 4, 2015 at 2:06pm UTC
"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 Mar 4, 2015 at 2:10pm UTC
Mar 4, 2015 at 2:29pm UTC
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!