Thread: char input and recognition - easy solution to help a newbie!

1. char input and recognition - easy solution to help a newbie!

Hey, I know there's a very simple explanation and a very simple answer to my question, I just don't know what it is as I am very new to C++

I am trying get my program to recognise an input of either N, S, E and W so that I can use if statements based on these values. This is for a bigger project concerning the aspect of a slope, and thus various other calculations depend on the slope, thus I need my program to be able to recognise the difference between an input of N, S, E or W.

At the moment I have this

Code:
```#include <iostream>

using namespace std;

int main ()

{

char aspect;

char N;
char S;
char E;
char W;

cin>>aspect;

cin.ignore();

if(aspect = N){
cout<<"\n\n north";
}

if(aspect =  S){
cout<<"\n\n south";
}

if(aspect =  E){
cout<<"\n\n east";
}

if(aspect =  W){
cout<<"\n\n west";
}

else cout<<"invalid input. quitting.";

cin.get();

}```
but this always gives me an output of "east" no matter what input I give it!
Any ideas why this is the case? Am I missing something obvious??

Thanks a lot

Jake

2. Since your comparing something to those values (N S E W), you need to give them a value first! Something like
Code:
```char N = 'N';
char S = 'S';
char E = 'E';
char W = 'W';```
Or you could even not use a variable at all, and whenever you compare just use the actual character itself, as shown below.

Next, your if statements will always be executed to true, because your assigning values, not comparing. You compare with two equal signs; one equal sign is to assign things, so do this instead:
Code:
```if(aspect == N){
// or you could do this, if you dont want to use these variables: if ( aspect == 'N' ) {
cout<<"\n\n north";
}```
Others might tell you to just use a "#define" or something, but I probably wouldnt take that advice and just understand the basics first, then learn things like that later.

3. cool, thanks a lot

4. #define is for C.

Here I would just use character literals ( if ( aspect == 'N' )). But if you do use variables, you should mark them const.

5. Code:
`if(aspect =  S)`
will (almost) allways be true since your assigning the value of s to aspect. To compare the values of aspect and S use "==" operator.

6. Why not use a switch here?
Code:
```cin >> aspect;
switch(aspect)
{
case 'N':
case 'n':
{
cout << "North" << endl;
break;
}
case 'S':
case 's':
{
cout << "South" << endl;
break;
}
case 'E':
case 'e':
{
cout << "East" << endl;
break;
}
case 'W':
case 'w':
{
cout << "West" << endl;
break;
}
default:
{
cout << "Invalid aspect supplied." << endl;
break;
}
}```