(2) Give the letter position in the alphabet, (e.g., user enters "e" and the program says, "e is the fifth letter of the alphabet).
(3) Ask if the user wants to quit or continue.
(Note that I have not coded the variations in grammar that result from different numbers; so the computer will output, "A is the 1th letter of the alphabet"; I wanted to write the core algorithm first)
It worked fine for a while, but then I made some change that caused the if condition not to execute consistently. Sometimes it works, sometimes it doesn't. So the user might be prompted to enter a letter ten times before triggering the if condition.
That could be because it looks like you're trying to get input from the user every iteration of a loop where you're initializing arrays and comparing that input rather arbitrarily to the current element you're setting (which has no relationship to the input except by sheer chance.)
#include <cctype>
#include <iostream>
charconst * ordinalEnding(int value)
{
// The teens all end in th.
if ( (value / 10) % 10 == 1 )
return"th" ;
switch ( value % 10 )
{
case 0: return"th" ;
case 1: return"st" ;
case 2: return"nd" ;
case 3: return"rd" ;
case 4: // fall-through is intentional.
case 5:
case 6:
case 7:
case 8:
case 9: return"th" ;
}
}
int main()
{
cout << "Enter letters (or a number to signal the end of input):\n" ;
char ch ;
while ( cin >> ch && !isdigit(ch) )
{
if ( isalpha(ch) )
{
// This is not portable.
int nth = tolower(ch)-'a' + 1 ;
cout << ch << " is the " << nth << ordinalEnding(nth) << " letter of the alphabet.\n" ;
}
}
}