Calculator problem

Hello,

I'm new to C++ and I'm stuck with a question. after reading the first 45 pages of this sites tutorial, i tried to make a calculator. I'm heppy with the result, but it is a bit slow to calculate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using namespace std;

float a;
float b;
string x;

int main () {
    loop:
    cout<<"Give first number > ";
    cin>> a;
    cout<<"Give operator > ";
    cin>> x;
    cout<<"Give second number > ";
    cin>> b;
    
    if (x == "*") {
    cout<<"\nSolution: "<< a*b <<"\n\n";
}
    else if (x == "/") {
    cout<<"\nSolution: "<< a/b <<"\n\n";
}
    else if (x == "+") {
    cout<<"\nSolution: "<< a+b <<"\n\n";
}
    else if (x == "-") {
    cout<<"\nSolution: "<< a-b <<"\n\n";
}
system ("pause");
    cout<<"\n";
goto loop;
}


You have to give in your first number, enter, operation, enter, second number, enter and you get the result. Is it possible to make a programme where you just type 2*7 and it says 14?

Thanks in advance,

Xander
Last edited on
Absolutely, it's possible. Just cin a number, one character, and another number. To shorten it to one line:
cin >> int >> char >> int;
Just one character. What you have there would work just fine as far as what you wanted if it was only one character instead of a string, or if you used a function for reading into strings that could be limited in terms of the number of characters to be read.

Expanding this to undefined-at-compile-time number of arguments, however, will be a petite problem.

-Albatross
Last edited on
Don't use goto unless you really have to. If you want an infinite loop, just say so:

1
2
3
4
while(true)
{
    //this will go on forever unless it hits a return or break statement
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

float a;
float b;
char x;

int main () {
    while (true) {
    cout<<"Give formula > ";
    cin>>a>> x>> b;

    if (x == "*") {
    cout<<"\nSolution: "<< a*b <<"\n\n";
}
    else if (x == "/") {
    cout<<"\nSolution: "<< a/b <<"\n\n";
}
    else if (x == "+") {
    cout<<"\nSolution: "<< a+b <<"\n\n";
}
    else if (x == "-") {
    cout<<"\nSolution: "<< a-b <<"\n\n";
}
system ("pause");
    cout<<"\n";
}
}


Wait im tring your solution now Albatross
Last edited on
I now get the error:

ISO c++ forbids comparison between a pointer and integer.
When you said

if (x == "*")

you actually meant

if (x == '*')

"*" is a string literal, while '*' is a character literal, which is what you want in this case.
Aye, it's a common misstake for beginners to use double-quotes (" ") instead of single-quotes (' ') for characters.
Thanks so much guys!
This is an awesome community :D
Topic archived. No new replies allowed.