Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: invalid conversion from ‘const char*’ to ‘char*’ [duplicate]

Tags:

c++

Possible Duplicate:
Using strtok with a std::string

#include<iostream>
#include <string>
#include <string.h>

using namespace std;

int main()
{
    string s("hello hi here whola");
    string background;
    char *strval;

    char* tok = strtok_r(s.c_str()," ",&strval);
    while(tok !=NULL)
    {
    cout << tok <<"\n";
    if (tok == "&")
        background = tok;
    else
    {
        statements1;
        statement2.. ;
    }
    tok = strtok_r(NULL, " ",&strval);
    }

    return 0;
}

output:

new.cpp: In function ‘int main()’:
new.cpp:13:47: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
/usr/include/string.h:359:14: error:   initializing argument 1 of ‘char* strtok_r(char*, const char*, char**)’ [-fpermissive]
like image 325
Kanha Avatar asked Jun 20 '26 08:06

Kanha


1 Answers

The s.c_str() returns a pointer to the const char to prevent you from modifying the backing up memory. You need to make a writable copy of this constant string say with strdup() function as strtok() really modifies the string that you are scanning for tokens.

like image 66
Serge Avatar answered Jun 23 '26 03:06

Serge