2
string str1 = "hello";
    const char* string1 = str1; 

I get an error..

cannot convert ‘std::string {aka std::basic_string}’ to ‘const char*’ in initialization

how do i cast string to const char*

Thanks for helping

billz
  • 43,318
  • 8
  • 77
  • 98
user1777711
  • 1,494
  • 5
  • 19
  • 31

3 Answers3

13

how do i cast string to const char*?

use std::string::c_str() function, it returns a non-modifiable standard C character array version of the string.

const char* string1 = str1.c_str();
billz
  • 43,318
  • 8
  • 77
  • 98
2

Try const char* string1 = str1.c_str();

Constantinius
  • 32,691
  • 7
  • 72
  • 83
-1

How about this solution:

string str1 = "hello";
const char* string1 = str1.c_str();
Alexander Mihailov
  • 1,144
  • 7
  • 15
Subhajit
  • 312
  • 1
  • 6