making your own strnlen function

Sep 25, 2018 at 6:06pm
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]
Last edited on Sep 25, 2018 at 6:34pm
Sep 25, 2018 at 6:10pm
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.
Sep 25, 2018 at 6:20pm
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.
Sep 25, 2018 at 6:35pm
@jonnin that wasn't supposed to be there I'm sorry
Sep 25, 2018 at 6:40pm
@helios, once I add the second parameter, what am I supposed to do next?
Sep 25, 2018 at 7:05pm
@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.

Don’t give up and Good luck!
Last edited on Sep 25, 2018 at 7:06pm
Sep 26, 2018 at 1:14am
thank you for your help, I was finally able to do it.
Topic archived. No new replies allowed.