How to return int from read character array?

I'm not sure how to return the int or how to fix the for loop properly.
Trying to return character count.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstring>
using namespace std;

int myStrLength(char *);
int SIZE =0;
int main()
{
    char countChar[] = {"Hello"};

    myStrLength(countChar);

}

int myStrLength(char * countChar)
{
    for (int i = 0;i< SIZE;i++)
{
      countChar[i];

      cout << countChar[i];
}
}
Last edited on
A c-string ends with a null character. Your loop should be adding 1 to a total for each character until it finds that zero char.
see the tutorial page,
http://www.cplusplus.com/doc/tutorial/ntcs/

Don't do the cout inside your function, instead return the total.

See function tutorial for examples of returning a value.
http://www.cplusplus.com/doc/tutorial/functions/

In main() you should call the function in the same way as you would call strlen.

1
2
    cout << "length = " << strlen(countChar) << '\n';
    cout << "length = " << myStrLength(countChar) << '\n';



Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int myStrLength(char *);

int main()
{
    char str[10] = {"Hello"};
    int len;
    
    
    len = myStrLength(str);
    cout << "STR length " << len << endl;
}

int myStrLength(char *str)
{
  int i; 
  int SIZE=0,count=0;

    for (i = 0;i < 10;i++)
{
      SIZE = *(str+i);
}
      return SIZE;

}


What did I write wrong because it doesn't increment at all.
Last edited on
It doesn't increment because you are not adding anything to SIZE.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int myStrLength(char *);

int main()
{
    char str[10] = {"Hello"};
    
    int len = myStrLength(str);
    
    cout << "STR length " << len << endl;
}

int myStrLength(char *str)
{
    int size = 0;

    // Loop until a character '\0' is found
    
    for ( int i = 0; str[i] !=  '\0' ; i++)
    {
        size++;
    }
    
    return size;
}
Geez. It was staring me right in the face and I couldn't see it. Thank you so much!!
Topic archived. No new replies allowed.