-1

I am trying to convert an integer to a char pointer as shown below. The data results are different. I am not sure what is going wrong. Please help me in correcting the code.

int main(){ 
    char *key1 = "/introduction";
    std::ostringstream str1;
    str1<< 10;   
    std::string data=str1.str();
    std::cout <<"The data value="<<data<<std::endl;  // The data value= 10
    char *intro= new char[data.length()+1];
    
    strcpy(intro, data.c_str());
    std::cout <<"The data value="<<*intro <<std::endl; // The data value=1
          
    return 0;
}

I am not sure why two data value are printed different i.e, 10 and 1.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Manu
  • 177
  • 9

1 Answers1

4

In C++, when trying to print all the contents of a char * with cout, you should pass the pointer, i.e. cout << intro << endl.

What you've done here is dereferenced the char *, so cout << *intro << endl is equivalent to cout << intro[0] << endl, which is equivalent to printing the first character, 1.

Ryan Zhang
  • 1,856
  • 9
  • 19