0

Below check is string and temp1->data is integer. I want to insert temp1->data into check. So I type cast int into const char*. This gives warning : cast to pointer from integer of different size [-Wint-to-pointer-cast]

Part of code:

  temp1 = head;
  std::string check;
  check = "";
  int i = 0;
  while(temp1 != NULL)
  {
    check.insert(i, (const char*)temp1->data);// here is the warning
    temp1 = temp1->next;
    ++i;
  }

I want to know what other choices I have to insert the integer (temp1->data) into string(check) using insert function and what is the actual effect of warning [-Wint-to-pointer-cast] on my code.

Points:

  1. data is integer, next is pointer to Node
  2. I'm trying to implement a function to check if a linked list containing single digit number is palindrome or not. Yes, I know other methods for this but I just want to implement through this method too.
  3. Here I want to store all the data of linked list into a string and directly check if the string is palindrome or not.

This question may seem duplicate of this . But it is not, here I explicitly asked for inserting integer into string using insert function contained in string class.

PS: on using std::to_string(temp1->data) gives me error ‘to_string’ is not a member of ‘std’.

Community
  • 1
  • 1
Ayushi bhardwaj
  • 441
  • 5
  • 18

2 Answers2

1

You can use std::to_string function to convert integer to string and then insert it in a string using insert function on std::string.

std::string check;
check = "";
int i = 0;

check.insert(i, std::to_string(10));

The reason you are getting error "to_string is not a member of std" is may be because you did not include <string> header.

Rao
  • 20,781
  • 11
  • 57
  • 77
Abhishek
  • 175
  • 8
0

First, here's a way to convert an integer to a string without much work. You basically create a stream, flush the int into it, and then extract the value you need. The underlying code will handle the dirty work.

Here's a quick example:

stringstream temp_stream;
int int_to_convert = 5;

temp_stream << int_to_convert;
string int_as_string(temp_stream.str());

Here's more info on this solution and alternatives if you want to know more: Easiest way to convert int to string in C++

Regarding the impact of the cast that you're doing, the behavior will be undefined because you're setting char* to an int value. The effect won't be converting the int value to a series of characters, instead you'll be setting the memory location of what the system interprets as the location of first character of a char array to the value of the int.

Community
  • 1
  • 1
mabeechen
  • 121
  • 5