There is a very beginner assignment. It suppose to be a C++ program, not a C program.
C++ has one, but C has no "string" data type. So i want to use arrays of characters to achieve the same functionality. It should be a C function to compute string length, prototype: int myStrLen(const char[])
And also the program should search for the null character, '\0'.
No pointer and no <cstring>.
Can anyone help me out? I have been stuck for 2 hours. :(
You have the right idea; have a variable that increments by one every time another character is read. When the character is a null-terminated character, the loop exits and the function returns the length of the string.
@vlad;
int myStrLen( const char[] )
you mean this?
int myStrLen( const char[] str )
Yes, it is a typo. I copied the declaration of the function from the original message and did not take into account that the identifier of the parameter is missed.:) Thanks, I updated my previous message.
But you also made a typo the same way as I did.:) Instead of
yes, you noticed it... good... :) i did it on purpose... it said that initialization is good programming practice... so i did initialized it (assign value after declaration) and then assign in again, when it's about to used...
well, maybe the purpose is avoiding your variable having a garbage value... my opinion, it's useful on long source code... but, in my opinion once again, it is good to initialize it because we don't know how long our code is going to be...
maybe the others can explained it better (or correctly)...
int myStrLen(const char str[])
{
int i = 0;
for(i = 0; str[i] != '\0'; i++) ;
return i;
}
But one thing is it didn't calculate \0 actually, when i input "derp", it displayed 4, "Hello" output is 5. But it suppose to count null terminator, should i just plus 1 or what? :/
The initial int i = 0; isn't necessary, as it is done in the for loop. Why do you want to count the null terminator in the string? The null is there so that the computer knows where the end of the string is.
I should say to please use code tags - the <> button on the right - it makes reading the code much easier as it formats it properly.
The initial int i = 0; isn't necessary, as it is done in the for loop. Why do you want to count the null terminator in the string? The null is there so that the computer knows where the end of the string is.
He wouldn't be able to return i if he removed that. The for loop ends before the null-terminated character is counted as a character of the string. His code is fine and functions properly, so there is little to nothing he could improve upon.