working with C-Strings

what is wrong with this input validation loop. Once it goes in the if statement it doesent come out.

1
2
3
4
5
6
7
8
9
10
11
int t = 0;
while(chWord[t] != '\0')
{
   if(!isalpha(chWord[t]))
   {	
       cout << "Error, a valid word should only contain letters.\n";
       cout << "Enter a word: ";
       cin >> userWord;
   }
   t++;
}
plz post your whole code
Well, if the loop is running infinitely, it's because your loop condition is always true.

In other words, your array chWord doesn't contain any null characters.
Or it doesn't have a null terminator on the end of the char array, or the char array is unititialised.
Well, yes - all of which are covered by "your array chWord doesn't contain any null characters".
Well, yes - all of which are covered by "your array chWord doesn't contain any null characters".


@MikeyBoy - no need to take that attitude, we're all only trying to help the chap.
would it be simpler to do this input validation if the word was a string object?
would it be simpler to do this input validation if the word was a string object?

Well, it's your code. A char array is fine, but with c and c++ is is advisable to initialise your variables first. When you declare a char array either on the stack or heap (i.e. new char[...] ) you must add sufficient room for the null terminating character and then you won't go far wrong.

If I declare a char array on the stack I normally do:

 
char szArray[STR_LEN+1] = {'\0'};


and if on the heap:

1
2
char* pszArray = new char[STR_LEN+1];
memset(pszArray, 0, STRLEN);


HTH

Andrew
Last edited on
Topic archived. No new replies allowed.