problem with Enums

closed account (zN0pX9L8)
I'm trying to make a program that takes a word the user inputs and turns it into corrisponding number s of the alphabet ie. a =1 b=2 a.s.o.

I think I have a little problem in the second forloop

How do I make it go through the 2nd for loop and access the enum alphabet?

//---------------------------------------------------------------------------

#include <vcl.h>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <iostream.h>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>

#pragma hdrstop
char UserInput [80];
enum alphabet {a = 1, b = 2, c = 3,d = 4,e = 5,f = 6,g = 7,h = 8,i = 9,j = 10,k = 11,l = 12,m = 13,n = 14,o = 15,p = 16,q = 17,r = 18,s = 19,t = 20,u = 21,v = 22,w = 23,x = 24,y = 25,z = 26 };
//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{

cout << " Enter A Word" <<endl;
cin >> UserInput;

vector <char> vWord;
// Takes word that user inputs and makes it into a vector
for (unsigned int i=0;i< strlen(UserInput);i++){
vWord.push_back (UserInput[i]);
}
for (int i = 0; i < 26; i++){
if ( UserInput[i]==alphabet[i]){
cout << alphabet[i]<< " " <<endl;
}
}



getch ();
return 0;
}
Last edited on
Well, you are doing it the hard way to use the enum at all... but you need to convert the letter to the enum

alphabet value = UserInput[ i ] -'a' + a;
This assumes that UserInput only contains characters in 'a'..'z'.

BTW, you are also playing a dangerous game by using global identifiers named 'a', 'b', 'c', etc...

A better way would be simply to get the index of the letter in the alphabet (where A = 1, B = 2, ..., and everything else = 0).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <cctype>
#include <string>

using namespace std;

int main()
  {
  string s;
  cout << "Enter something> ";
  getline( cin, s );

  for (int i = 0; i < s.length(); i++)
    cout << s[ i ] << " = " << (isalpha( s[ i ] ) ? (toupper( s[ i ] ) -'A' +1) : 0) << endl;

  return 0;
  }


Hope this helps.
Last edited on
closed account (zN0pX9L8)
thank you, but I don't understand this part of the line of the code

isalpha( s[ i ] ) ? (toupper( s[ i ] ) -'A' +1) : 0) << endl;
It is equivalent to:

1
2
3
4
5
6
7
8
if (isalpha(s[i]))
{
   (toupper( s[ i ] ) -'A' + 1)  << endl;
}
else
{
   0 << endl;
}

Topic archived. No new replies allowed.