Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert string to const char

I have this function and the compiler yells at me saying "Cannot convert string to const char".

void 
DramaticLetters(string s, short TimeLength)
{
    for(int i = 0, sLen = strlen(s); i < sLen; i++){
        cout << s[i];
        Sleep(TimeLength);
    }
}

There's something wrong with the strlen, I think

like image 415
user1575615 Avatar asked Jul 23 '26 16:07

user1575615


2 Answers

strlen() is for C const char* strings. To get the length of a string s, use s.size() or s.length(). If you want to get a C string from a string, use s.c_str().

Although C++ makes it seem that const char* and string are interchangeable, that only goes one way when converting const char* to string.

There is no reason why you would want to use strlen either. strlen is most likely defined with a loop, which will never be as efficiant as size(), which is most likley just a getter for a length property of the string class. Only convert string to C strings when calling C functions for which there is not a C++ alternative.

like image 67
Linuxios Avatar answered Jul 26 '26 05:07

Linuxios


You should not mix C and C++ string functions. Instead of strlen() (a C-style function), use string::size():

for(int i = 0, sLen = s.size(); i < sLen; i++) {
    cout << s[i];
    Sleep(TimeLength);
}

Here you have a reference with all methods from class string.

like image 21
betabandido Avatar answered Jul 26 '26 05:07

betabandido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!