Getting problem while executing strlen() in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • saiavinashiitr
    New Member
    • Mar 2014
    • 16

    #1

    Getting problem while executing strlen() in C++

    when i am executing cout<<strlen("a vinash"); in the main function, i am getting output as 7....but whereas if i execute as following

    #include <iostream>
    #include <cstring>
    using namespace std;
    int main()
    {
    string a = "avinash";
    cout<<strlen(a) ;
    }

    Now, i am getting an error that cannot covert std::string ot const chat* for argument 1 to size_t strlen(const char*)

    but if do using string length, i am getting the perfect answer

    #include <iostream>
    #include <string>
    #include <cstring>
    using namespace std;
    int main()
    {
    string a = "avinash";
    cout<<a.length( );
    }

    Now i am getting the correct output as 7

    can u please tell me why i am unable to get the same output using cout<<strlen(a) ;
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You cannot use strlen on a C++ string object. strlen assumes a null-terminated char array. A sring object my not have that structure.

    You are supposed to use the size() method of string.

    You can, however, tell the string object to produce a C-style null terminated string by using the c_str() method:

    Code:
     cout<<strlen(a.c_str());

    Comment

    Working...