Hello,
I am working on a program that counts the total number of characters in a string without using the strlen (string) function. When I run the program it just gives me some random number. I think the main body is fine there is just something wrong with the function that I created. This is my code so far:
Either way, I don't think you can count a single character... You need to be counting character arrays, not single chars.
And... I understand you probably don't know the answer yourself, so don't worry about it, but... What on earth is the point of using C++, if you can't use strings, and you have to use char arrays and... yeah. You might as well use C with strlen().
If this is an assignment, I hate to say, but it's a bad one.
Just in case I am not stating the problem right, here it is word for word:
The standard library function strlen() (found in string.h) returns the number
of characters in a string, not including the terminating NUL ('\0') character.
Write your own StringLength() function that does exactly the same thing.
Write a short main() program to declare and initialize a string. Pass the
string to StringLength() to demonstrate that it can return an integer value
representing the number of characters in the test string. Use a cout
statement in main() to print out the length of the string.
Please note: Your function should count the characters in the string, not
access some C++ library function or method. DO NOT #include <string.h> or
<string>.
Well, you're talking about C-style strings. C++ strings require the <string> standard header. You shouldn't say "string" when you mean "C string".
Basically, you could do what helios showed. A more beginner-friendly version would be this:
1 2 3 4 5 6
int my_strlen(constchar* str)
{
int n = 0;
for(constchar* p = str; p != 0; ++p, ++n);
return n;
}
In your original version, you were only considering letters, thus excluding all other character, and the initialization part of your for loop wasn't really initializing anything. You were also adding character values to the size variable, rather than 1.
In case you aren't aware, in C++ a convention was established to terminate all strings with a null character (written as 0 or '\0'). Thus, to understand what filipe posted, you should realize that he is merely parsing the given string for this null/terminating character.