Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

newbie ? - > cin - compare letter "A" to "F" 1

Status
Not open for further replies.

Trope

Programmer
May 14, 2001
110
US
I am a newbie... trying to make this simple program accept a character input A-F. If not A-F give a message and get another character.

This is not working, does anyone see my mistake?

Code:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
  // Init user input
  char licenseLetter;
  bool inputValid = false;
 // Get user input
  do
  {
  	cout << "Enter selection letter: ";
  	cin >> licenseLetter;

	// Validate
	if(licenseLetter<"A" || licenseLetter>"F"){
		cout << "Invalid Selection. A-F only, please." << endl;
	} else {
		// ok, move on and do other stuff
		
		inputValid = true;
	}
  } while (inputValid == false);

cout << "You entered: " << licenseLetter << endl;

return 0;
}

Any help would be greatly appreciated.

Regards,
Trope

 
> if(licenseLetter<"A" || licenseLetter>"F")
Use single quotes for single letters
if(licenseLetter<'A' || licenseLetter>'F')


--
 
[tt]'A'[/tt] and [tt]"A"[/tt] are two very different things.


[tt]'A'[/tt] is the character (that is, a single [tt]char[/tt]) A.

[tt]"A"[/tt] is a string (that is, a null-terminated array of [tt]char[/tt]) consisting only of the character A.


Performing a built-in operation on a character is equivalent to performing it on the ASCII (usually) value of the character.

Performing a built-in operation on a string is equivalent to performing it on the address of that string in memory.


Thus, the expression
Code:
licenseLetter<"A"
is comparing the ASCII value of [tt]licenseLetter[/tt] with the memory address of a compiler-generated string "A," which is an operation not likely to make sense.

Using
Code:
licenseLetter<'A'
compares the ASCII value of [tt]licenseLetter[/tt] with the ASCII value of A (0x41). That makes more sense.


As an aside, you should know that your code is not guaranteed to work everywhere.

If [tt]licenseLetter[/tt]'s value is between A's value and F's value, it doesn't necessarily follow that [tt]licenseLetter[/tt] is one of A, B, C, D, E, and F. That will be true if ASCII is being used, but what if your system was using a character set that put the characters in a different order?

e.g.:
Code:
... A a B b C c ! ? . ; : 1 2 3 4 5 6 7 8 9 0 D d E e F ...

Anyway, that's not something you need to worry about when you're just starting, but I just thought you might like to know the problem exists.
 
Terrific information, thanks to both of you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top