help with alphabetic characters

How can I make a program where i can verify if the user input contains alphabetic characters and if the user input is a number i have to output the...

here is part of my code... I have tried it for hours but it does not work

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
   # include <iostream>
   # include <cstdlib>
   # include <string>

   using namespace std;


  int main ()
  {
      string name;

      cout<<"What's your first name?"<<endl;
      cin>> name;

    //int y=32;
     int z= atoi (name.c_str());


      for ( int y=z; y<z; y++)
      {
        char w=y;

      if (isalpha(w))
      {
          cout<<"Valid name."<<endl;
      }
      if(isalnum(w))
      {
           cout<<"your name cannot contain:"<<y<<endl;
           cout<<"invalid name."<<endl;
      }

      }

  }
Read this: http://www.asciitable.com/

You'll notice that characters are given values 97-122 for lower case, and 65-90 for upper case. This means that a lower case letter, a, has an asci code of 97. Which implies that...
char ch = 'a';
char ch = 97;
Have the same value. This applies for all other values within the asci table.

So, if you would like to test if something ISNT a letter (upper case, or lower case), then you could do this:


1
2
3
4
5
6
7
8
9
10
11
    string name;
    cin >> name;
    for(unsigned short i = 0; i < name.size(); i++)
    {
        if( ((name[i] >= 65) && (name[i] <= 90)) || ((name[i] >= 97) && (name[i] <= 122)) )
        {
            // This will evaluate to true if the character is a letter, upper or lower case
        } else {
            // Otherwise, you can print an error message here
        }
    }
Last edited on
It may be easier to get the correct values if it's done this way:
if( ((name[i] >= 'A') && (name[i] <= 'Z')) || ((name[i] >= 'a') && (name[i] <= 'z')) )


or

1
2
3
4
5
        char c = tolower(name[i]);
        if (c < 'a' || c > 'z')
        {
            cout << "Not a to z: " << c;
        }


or

1
2
3
4
        if (!isalpha(name[i]))
        {
            cout<<"Not alphabetic: "<< name[i] << endl;
        }

Topic archived. No new replies allowed.