简体   繁体   中英

Passing string as argument

//EDITED: follow up question:

But making the function as isUnique(const char *s) and then calling function as isUnique(str.c_str()) does not allow me to modify my string str in the function
//

I am having problem with passing a string:

bool isUnique(char *s)
{
    int arr[256] = {0};
    while(*s)
    {
        arr[*s]++;
        if(arr[*s]>1)
        {
            cout<<"not unique";
            return false; 
        }
    }
}
int main()
{
    string str = "abcda";
    cout<<"1: True : unique, 2: False: Not Unique"<<endl<<isUnique(str);
}

ERROR:cannot convert 'std::string {aka std::basic_string}' to 'char*' for argument '1' to 'bool isUnique(char*)'

Pass the argument as:

isUnique(str.c_str());

And make the parameter type of the function as const char* :

bool isUnique(const char *s)

Because std::string::c_str() returns const char* .

Or even better, make the parameter const string& :

bool isUnique(const std::string & s);

And pass as you do : isUnique(str) . Inside the function you can use s[i] to access the characters in the string, where 0 <= i < s.size() .

Use

isUnique(str.c_str())

and make sure isUnique takes a char const * argument.

You are not passing a string. You are passing a char * and trying to create one from a string . Of course the conversion from string to char * is not automatic - they are two very different things.

I suggest that you write this function:

bool isUnique(const std::string& s)

Either change function to accept

bool isUnique(const string& s)

and pass the string as a const reference

or do as the two other fine people suggested.

This being C++ it would be preferable to pass a const std::string& unless of course you have to be compatible with some C code or just have a requirement of using C-strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM