When a string is given as input, the compiler will append a null-character (
'\0') at the end of the string. When this character is encountered, you know that the string ends there. Because this character has the value of zero, it corresponds to the Boolean value of false. So far, you're on the right track, but you're not counting the string length properly. Here's how I would do it given your restrictions:
1 2 3
|
int iLength(0);
for(int iIndex(0); Name[iIndex]; ++iIndex)
++iLength;
|
This code is very simple. Let's walk through it:
First we declare "
iLength", which we use to store the length of the string. Then, we begin a loop. The initialisation section of the loop introduces "
iIndex", which represents the index of the character we're accessing. To understand why we have this, we must look into the condition section of the loop. The condition tests for a character, other than the null-character (remember what I said about it above?). If the null-character is encountered, the condition evaluates to false, and the loop ends. However, any other character is counted. So, if the "
iIndexth" character in "
name" is a null-character, the loop will stop. The increment section of the loop is straight forward; move to the next character.
Wazzak