if condition inconsistent

I wrote an exercise program on arrays and ASCII.

It's supposed to:

(1) Prompt the user for a letter.

(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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
///////////////////
// Arrays, ASCII //
///////////////////

#include <iostream>

using namespace std;

void letterassignment ()

{

  char upper [26], lower [26], letter;

  for (int n = 1; n < 27 && n > 0; n ++)

  {
    cout
    
    << "\n\n"
       
    << "Enter a letter of the alphabet: ";
       
    cin 

    >> letter;

    upper [n - 1] = 65 + (n - 1);
    lower [n - 1] = 97 + (n - 1);
   
    if ( (letter == upper [n - 1]) || (letter == lower [n - 1]) )
        
    {

        cout 
      
        << "\n\n"

        << letter << " is the "
	<< n 
        << "th"
        << " letter of the alphabet."
 
        << "\n\n"

        << "Enter 0 to quit, 1 to continue: ";

        cin 

        >> n;

    }
  
  }
 
}

int main ()

{

  letterassignment ();

  return 0;

}
Last edited on
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.)


Just for fun:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <cctype>
#include <iostream>

char const * 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" ;
		}
	}
}
Last edited on
Topic archived. No new replies allowed.