I am trying to replicate the function strnlen, but I am having trouble making the function return the length of a string up to a certain maximum length.
int mystrnlen (char str[]) {
int c = 0;
while (str[c] != '\0')
c++;
return c;
}
int main() {
char str[100];
std::cin >> str;
std::cout << mystrnlen(str, 50);
}
Put the code you need help with here.
[/code]
strlen() is supposed to take a second parameter of type size_t, which is the maximum length that the function is allowed to read from its const char * parameter.
if you want total compatibility you may want to make it take char* and check that for null first thing.
char* will accept an array, so you can keep str as it is and it will still work.
int length = str[50]; <--- this makes no sense. you assigned length from an uninitialized location.
you don't need this at all. length belongs in the function as helios is saying.
@rolando flores
It is very difficult to help people with really simple stuff when they (you) are not putting any effort into it.
It helps to read the descriptions of the two functions:
• strlen( s ) — return the number of characters in a string
• strnlen( s, max ) — return the number of characters in a string or max, whichever is smaller.
You have written a function to find the number of characters in a string. What change can you make to that function to make it stop if you have counted max characters so far?
The point of exercises like this is to help you develop this reasoning ability. Yes, it is a pain, and often a struggle, but you cannot really learn without the effort.
Sure, someone could just post the answer for you, but then you would not learn how to move your mind to solve the problem — you would only have learned one trick for a very specific scenario.