Program doesn't work as supposed
Oct 2, 2010 at 9:43am UTC
okay here is code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
using namespace std;
int main() {
int a,b,rez;
char choice[1];
cout<<"First: " ;
cin >> a;
cout<<"\nChoice: " ;
cin >> choice;
cout <<"\nSecond: " ;
cin >> b;
if (choice == "+" ){
rez = a + b;
cout<<"Result: " <<rez;
}
else if (choice == "*" ){
rez = a * b;
cout<<"Result: " <<rez;
}
system("PAUSE" );
return 0;
}
my program doesn't output result at all?
what do I do wrong herE?
thank you
Oct 2, 2010 at 10:02am UTC
your problems are on lines 13 and 17.
"+" and "*" are string literals that are allocated on the heap so there are addresses associated with them. choice is an automatic variable located on the stack. When you use ==, you are comparing the two addresses - they will never equal.
What you want is:
1 2 3 4 5 6 7
#include <string.h>
// ...
if ( !strcmp( choice, "+" )) {
// ...
} else if ( !strcmp( choice, "*" )) {
// ...
}
Or, you can declare choice as a character and compare against characters:
1 2 3 4 5 6 7
char choice;
// ...
if ( choice=='+' ) {
// ...
} else if ( choice=='*' ) {
// ...
}
If you still want to use strings, but avoid C-like code and strcmp(), you should google std::string and use it in place of char choice[1]
There are many ways to skin this cat.
Last edited on Oct 2, 2010 at 10:08am UTC
Oct 2, 2010 at 10:10am UTC
choice == "+"
This is not how you compare cstrings.
a few options:
choice is one char, so why not use one char?
1 2
char choice;
if (choice == '+' )...
If you ever want to do this with longer cstrings
1 2
char choice[50];
if ( strcmp(choice, "+" ) == 0 )...
Though it would be better to use std::string
1 2 3 4
#include <string>
...
std::string choice;
if (choice == "+" )...
edit: too slow..
Last edited on Oct 2, 2010 at 10:14am UTC
Topic archived. No new replies allowed.