I am trying to write my own strlen fuction, and call it inside main. I feel so close, but I cannot figure out why I get an invalid conversion from 'char*' to 'char' Here is my code:
#include <iostream>
usingnamespace std;
char ch[999];
int StringLength(char ch);
int main ()
{
cout << "Enter a string, and I will output the number of characters contained therein." << endl;
cin.getline(ch, 999);
cout << StringLength(ch);
}
int StringLength(char ch)
{
for (int i = 0, int c = 0; ch[i] != '\0'; i++, c++)
return c;
}
My error message is as follows: "error: invalid conversion from 'char*" (I guess this is the right symbol used after char) "to 'char' [-fpermissive]
Any help will be greatly appreciated! Thanks
Giving a variable in one scope a name that matches the name of a variable in another scope does not make those names refer to the same variable.
You StringLength has a single char as it's sole parameter. You cannot feed a function which expects a char a pointer-to-char.
Also, your StringLength is equivalent to:
1 2 3 4
int StringLength(char)
{
return 0;
}
Assuming the character fed to it is not '\0'. If it is, you have undefined behavior, because the function returns nothing despite it's promise to always return something.
As I can see, I will need to read a little further into my book tomorrow morning. I haven't been over pointers and have never seen an example of the "const char*"
Here is what my code looks like after updating it as much as I can tonight. as I really need to get to bed.
#include <iostream>
usingnamespace std;
char ch[999];
int StringLength(constchar* ch);
int main ()
{
cout << "Enter a string, and I will output the number of characters contained therein." << endl;
cin.getline(ch, 999);
cout << StringLength(ch);
}
int StringLength(constchar* ch)
{
for (int i = 0, c = 0; ch[i] != '\0'; i++, c++)
if (ch[i] == '\0')
return c;
}
I'm getting a garbage return value, so I am assuming that there is something wrong with my for loop and it never adds to the counter c. I will continue working on this problem in the morning, as I am too tired to continue tonight. Any pointers would be nice, but I will also read more on the s subject
The condition governing your for loop is ch[i] != '\0'. So, the for loop does not execute when ch is '\0', meaning that the condition on line 19 will never be true, which means that your function never returns anything.
I just jumped back onto the program to see if I could think more clearly now that I've had some rest, and came up with this ( I haven't finished reading the chapter yet like I should.)
1 2 3 4
if (ch[i] != '\0')
for (;ch[i] != '\0'; i++, c++)
if (ch[i] == '\0') break;
return c;
Can anyone tell me if there is a more efficient test here? This seems to work though. It counts white spaces, and I am unsure if that is desirable or not. Thanks everyone for the help so far