Nov 18, 2014 at 6:07pm UTC
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 Nov 18, 2014 at 8:15pm UTC
Nov 18, 2014 at 8:16pm UTC
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 Nov 18, 2014 at 8:17pm UTC
Nov 19, 2014 at 2:03am UTC
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)
Nov 19, 2014 at 4:28am UTC
I see, so there is any other way to test if each element is a letter. Sorry if I'm responding so late.
Nov 19, 2014 at 4:05pm UTC
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.