-
switch using enum
Can someone please tell me why my output is always a 1 in my simple switch statement
Code:
#include <iostream>
using namespace std;
int main() {
enum switcher {off, on};
char* state;
switcher switch_state;
cout << "Enter switch state:";
cin >> state;
if (state == "off")
switch_state = off;
else
switch_state = on;
cout << switch_state << endl;
system("PAUSE");
return 0;
}
Thanks
-
Maybe you shouldn't declare state as a pointer, since the input is coming directly from the user. Though I might be wrong, my experience with enum is pretty green.
-
> char* state;
This is an unallocated pointer
Try
char state[100];
> if (state == "off")
This just compares pointers
Try
if ( strcmp( state, "off") == 0 )
-
-
And as is often the case, just using the standard string class makes the fix even easier. Here is your original code using a string. All I did was switch the char* to string and add the <string> header. No need to use strcmp or set the size of the char array:
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
enum switcher {off, on};
string state;
switcher switch_state;
cout << "Enter switch state:";
cin >> state;
if (state == "off")
switch_state = off;
else
switch_state = on;
cout << switch_state << endl;
system("PAUSE");
return 0;
}