why this doesn't work with char ?
Feb 25, 2013 at 6:03pm UTC
i made a simple calculator using floats and string:
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include <iostream>
#include <string>
using namespace std;
float add(float num1, float num2){
return num1+num2;
}
float sub(float num1, float num2){
return num1-num2;
}
float mol(float num1, float num2){
return num1*num2;
}
float div(float num1, float num2){
return num1/num2;
}
int main (){
string input;
float num1;
float num2;
cin >> num1;
do {
cin >> input;
if (input=="+" ){
cin >> num2;
cout << add(num1, num2) << endl;
}
else if (input=="-" ){
cin >> num2;
cout << sub(num1, num2) << endl;
}
else if (input=="*" ){
cin >> num2;
cout << mol(num1, num2) << endl;
}
else if (input=="/" ){
cin >> num2;
cout << div(num1, num2) << endl;
}
else {
cout << "decide to add, sub, molt or div" << endl;
}}
while (input!="+" & input!="-" & input!="*" & input!="/" );
system("pause" );
return 0;
}
This properly works, but if i try to change string input at line22 with for example char input [50] i always got else (cout << "decide to add, sub, molt or div" << endl;) after cin >> input. Can anyone explain me why this happens ?
thanks
Feb 25, 2013 at 6:06pm UTC
You'd also need to change the if statements to check for a char literal:
if ( input == '+' )
Note, the single quotes, not double.
Double quotes, would be checking for a char *.
Topic archived. No new replies allowed.