Thread: Trouble passing a string into strlen()...

  1. #1
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204

    Thumbs up Trouble passing a string into strlen()...

    Why is it that this won't work?

    Code:
    #include<string>
    #include<iostream>
    
    using namespace std;
    
    int main()
    {
        string text=("This is Text");
        cout<<strlen(text);
        cin.get();
        return 0;
    }
    These are the errors I get:

    Code:
    no matching function for call to `strlen(std::string&)'
    candidates are: size_t strlen(const char*)
    Just to make things a little more clear, I want to keep the variable 'text' as a string and not a char array.

    Thanks

  2. #2
    Registered User
    Join Date
    Jan 2007
    Posts
    330
    text.c_str()

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    then use it as a string and through away the strlen function.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    text.length() does the same thing as strlen(text.c_str()), and with less effort.

    strlen() is meant to be used on C strings (char arrays), not C++ strings. In a C++ string, there is an actual length field [although it is not STRICTLY NECESSARY to implement it that way], so the length can be had immediately, rather than by "counting each character until we find a NUL character].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204
    Thanks everyone, that helps a lot!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. Passing an array into a function
    By Ryston in forum C++ Programming
    Replies: 4
    Last Post: 08-29-2006, 05:20 AM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. string handling
    By lessrain in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 07:36 PM