passing strings and using strlen

This is a discussion on passing strings and using strlen within the C++ Programming forums, part of the General Programming Boards category; I have a string in main and I want to be able to determine it's length in function Foo. void ...

  1. #1
    Unregistered
    Guest

    passing strings and using strlen

    I have a string in main and I want to be able to determine it's length in function Foo.

    void Foo(string S);

    main()
    {
    char S [15];

    Foo(s);
    }

    void Foo(string S)
    {
    int Length;

    Length = strlen(S);
    }


    When I complile, I keep getting this error message: cannot convert 'S' from type 'string' to 'const char *'

    What am I doing wrong?

    Thanks,
    Buzz

  2. #2
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    You can either use a pointer to an array of characters (char* or char[]) or the standard STL string class.

    If you want to use the first method, then include the <cstring> header, and in the std namespace is strlen(). For example:
    Code:
    #include <cstring>
    using namespace std;
    
    int main()
    {
        char* str = "Hello!";
        int length = strlen(str);
        return 0;
    }
    The other option uses the string from the <string> header, and that class has its own length function.
    Code:
    #include <string>
    using namespace std;
    
    int main()
    {
        string str = "Hello!";
        int length = str.length();
        return 0;
    }
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21