Question about the difference of string and char

Write your question here.
I do not know why in the following code only d="abc" succeed.
when I use the code string s="abc";
then s can not be converted to const char* while "abc" could?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
using namespace std;

int main() {
  char i ='n';
  i='j';
  string s="abc";
  const char* c;
  const char* d;
  const char* e;
  c=s;
  d="abc";
  e='a';
} ///:~
s is a std::string and c is a c-style string. You can put s into c with:

c = s.c_str(); // function returns a const char *

likewise e is a c-style string and 'a' is just an integer (char) so not compatible.

d = "abc"; // perfectly fine to initialize a const char * with a string literal.
Topic archived. No new replies allowed.