IsAlpha function not accepting my input.

So the purpose of the isalpha function is that it only accepts letters(a-z) but that doesn't seem to be the case for my code. If I input the letter p, the error message is displayed. If input a word like "city", the error message is still displayed. What's wrong with my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main()
{
    const int SIZE = 10;
    char letter[SIZE];

    cout << "Enter a word. ";
    cin.getline(letter, SIZE, '\n');

    while(!isalpha(letter[SIZE]))
    {
        cerr << "Error, only letters are allowed. ";
        cin.getline(letter, SIZE, '\n');
    }

    cout << "This is acceptable. ";

    return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main()
{
    const int SIZE = 10;
    char letter[SIZE];

    cout << "Enter a word. ";
    cin >> letter[SIZE];

    while(!isalpha(letter[SIZE]))
    {
        cerr << "Error, only letters are allowed. ";
        cin >> letter[SIZE];
    }

    cout << "This is acceptable. ";

    return 0;
Last edited on
So for some reason the second piece of code works but the first one constantly loops the error message no matter what. Can someone please explain?
Last edited on
isalpha() only tests a single char.

Line 15 only tests letter[10] which is only one element.

i.e. letter[] = "hello",
letter[0] = 'h'
letter[1] = 'e'
letter[2] = 'l'
letter[3] = 'l'
letter[4] = 'o'
letter[5] = '\0'; (string terminator)

Testing isalpha[4] would be true, isalpha[5] would be false (its not a letter, its \0)
I see, so there is any other way to test if each element is a letter. Sorry if I'm responding so late.
Well, in C, you have to walk through the whole string and test each element separately. C++ might have a string method to determine this, but this is probably just as easy.
Topic archived. No new replies allowed.