Join TSR now and get all your revision questions answeredSign up now

C++ function Watch

    • Thread Starter
    Offline

    1
    ReputationRep:
    I need a function that takes a reference to a string object and that converts the contents of the string to uppercase.

    Code:
    string function(string s) {
    	for (int i = 0; i < strlen(s); i++)
    		s[i]=toupper(s[i]);
    	return s;
    }
    When I compile, I get the error: Cannot convert 'string' to 'const char *'. Please help.
    Offline

    0
    ReputationRep:
    Hello Thomas.

    strlen takes a C-style string as an argument, not a std::string, therefore you must use s.c_str() as the argument when calling strlen.

    Here is the function prototype
    Code:
    size_t strlen ( const char * str );
    • Thread Starter
    Offline

    1
    ReputationRep:
    (Original post by Jiggle)
    Hello Thomas.

    strlen takes a C-style string as an argument, not a std::string, therefore you must use s.c_str() as the argument when calling strlen.

    Here is the function prototype
    Code:
    size_t strlen ( const char * str );
    I can use s.size() either, right?
    Offline

    0
    ReputationRep:
    Yes, s.size() would work fine also.
    Offline

    2
    ReputationRep:
    Code:
    string::iterator it;
    for ( it=str.begin() ; it < str.end(); it++ )
         *it = toupper(*it);
    
 
 
 
Poll
Is GoT overrated?

The Student Room, Get Revising and Marked by Teachers are trading names of The Student Room Group Ltd.

Register Number: 04666380 (England and Wales), VAT No. 806 8067 22 Registered Office: International House, Queens Road, Brighton, BN1 3XE

Quick reply
Reputation gems: You get these gems as you gain rep from other members for making good contributions and giving helpful advice.