Check if char is in array?

user inputs char
1
2
char c;
cin >> c;


Now I have an array with an alphabet in it. A thru Z.

Want to create a check to see if user inputted a correct char.

I found a C code for doing this, didn't understand it.

maybe:
1
2
3
4
5
if (c == alphabet[c+1])
//move code forward
else
//otherwise go back
// and re-enter char 


i doubt that works, but logic is PERFECT. just. like. me.

closed account (48T7M4Gy)
LMAO

What's this the incremental homework game?
no the homework is done, i'm just doing this to put checks on all of my user inputs. purely out of interest.

all i needed to do for homework was to create a 2d array of airplane seats. I just want to know how to run a check on an array with letters in a function.
closed account (48T7M4Gy)
It depends on what you are trying to do exactly but one way of finding out where in the alphabet array the input letter is would be

char c;
cin >> c;

int position = 99;
for(int i = 0; i < 26; i++ )
{
if ( c == alphabet[i] )
position = i;
}

Obviously with a full alphabet you'll always get a hit, but position = 99 is a simple way of knowing there was no hit.



Really depends. Pay attention to what's inside your array @OP, as alphabet a-z is not the same as A-Z. If you're just checking for validity, what @kemort said would be fine, and all you'd need to do is make that a boolean or something.


As for the code you were trying to do, no it doesn't work because as you might know, characters in C++ are also given numeric integer representations. However, depending on the operating system and the size of the bus (to the best of my knowledge) they are pretty much never going to start at 1. I think most systems use standard ASCII. But anyways, what you wrote is basically:

1
2
if( some character value == the value at the INDEX of the array of the value of the character you input + 1)
    // do stuff 


In other words, using a standard ASCII table, the value of character 'a' is 97. Do you have 97 slots in your array?
closed account (48T7M4Gy)
In other words, using a standard ASCII table, the value of character 'a' is 97. Do you have 97 slots in your array?


YFGHNG there is a relevant history to this OP that you may not be aware of. It's a follow on from:
http://www.cplusplus.com/forum/beginner/178362/
Last edited on
Topic archived. No new replies allowed.