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

}

int strlength(&a)
{
    for(int i=0;str[i]!='\0';i++)
    {
        int count++;
    }
    cout<<"The length of string is::"<<count;
}
4
Contributors
4
Replies
5
Views
4 Years
Discussion Span
Last Post by pinaka
1

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 by NathanOliver

1

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.

1

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++){
        count++;
    }
    cout<<"strlenght(): "<<count<<endl;
    cout<<"string.size(): "<<(int)str.size()<<endl;
}

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

Edited by Lucaci Andrew

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.