int strlength(&a);
using namespace std;
int main()
  string s1,s2;
  cout<<"Enter the strings u want to check length::";
  return 0;


int strlength(&a)
    for(int i=0;str[i]!='\0';i++)
        int count++;
    cout<<"The length of string is::"<<count;

So what is your problem? From what I can see you dont define count in your strlength function. As far as I can remeber strings from the string type are not terminated with a '\0'. You can you the size() function to find the legnth of the string. You would do that by nameOfString.size().

Edited 4 Years Ago by NathanOliver

This approach won't work on C++ string objects, at least not consistently. The string class does not use zero-delimiters to check the length of a string, but rather keeps a private size variable that is updated automagically as the string gets manipulated.

In any case, the string class has a built-in size() method. If you need the length of a string, use that.

strlen function from the #inclue <string.h> header, from the C library indeed calculates the size of the strig, having as a final delimiter the '\0' character, but strings in C++ are objects, which are not handled having as the last character the '\0' character. If you do want to use your function on string objects, and still get the right answer, you'll have to convert that string object to a C like string using the .c_str() function from the string class.
Have a look at it: Click Here
A quick example:

#include <iostream>
#include <string>
using namespace std;
void strlength(string str){
    int count=0;
    for(int i=0;str.c_str()[i]!='\0';i++){
    cout<<"strlenght(): "<<count<<endl;
    cout<<"string.size(): "<<(int)str.size()<<endl;

int main(){
    string a="Hello world.";
    return 0;

Edited 4 Years Ago by Lucaci Andrew

This article has been dead for over six months. Start a new discussion instead.