strlen() not working with string variable

12,064

strlen is a function from C and works with C strings (char *).

For proper C++ std::strings use the .length() or .size() member functions.

In fact most standard headers that start with 'c' include functions that C++ inherited from C. In your case you most likely don't have any reason to use <cstring> if you're already working with C++ strings.

Share:
12,064

Related videos on Youtube

Waters Sharma
Author by

Waters Sharma

BY DAY : I am currently intern at classic tech working in web development department. In code Ignitor framework. IN the Morning :I am also a BSc.C.S.I.T student . AND Night I am working on some projects in JAVA

Updated on July 10, 2022

Comments

  • Waters Sharma
    Waters Sharma almost 2 years
    #include <iostream>
    #include <string>
    #include <cstring>
    
    
    using namespace std;
    
    int main()
    {
        string b="hello";
    
        cout<<b;
    
        int c = strlen(b);
    
        cout << "Hello world!" <<c<< endl;
        return 0;
    }
    

    When I try to run this I get the error below

    ||=== Build: Debug in strlen (compiler: GNU GCC Compiler) ===|
    C:\Users\Waters\Desktop\hellow world\strlen\main.cpp||In function 'int main()':|
    C:\Users\Waters\Desktop\hellow world\strlen\main.cpp|14|error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'size_t strlen(const char*)'|
    ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
    
    • dgsomerton
      dgsomerton almost 8 years
      try strlen(b.c_str())
    • dgsomerton
      dgsomerton almost 8 years
      even better: try c = b.length()
    • Nick Matteo
      Nick Matteo almost 8 years
      @WatersSharma: because strlen takes a char * argument, not an std::string, which is totally meaningless to it. std::string::c_str() is a function returning a C string (const char *).
    • dgsomerton
      dgsomerton almost 8 years
      @WatersSharma: if you bothered to read the error message, it says right there: cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'size_t strlen(const char*)'
    • molbdnilo
      molbdnilo almost 8 years
      Whatever source you're learning from, throw it out and get a decent book.
    • Zulan
      Zulan almost 8 years
  • cwschmidt
    cwschmidt almost 8 years
    You surely meant, C strings must be terminated by '\0' not by '\n'.
  • Peregrin
    Peregrin almost 8 years
    @cwschmidt aha, you are damn right :D I should probably get some sleep
  • coyotte508
    coyotte508 almost 8 years
    also const char *b instead of char *b.
  • Peregrin
    Peregrin almost 8 years
    @cwschmidt well, in the example string isn't const
  • cwschmidt
    cwschmidt almost 8 years
    @Peregrin What do you refer to? It's irrelevant if it's const or not, C strings have to be terminated by '\0'