Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert from int to char*?

The only way I know is:

#include <sstream> #include <string.h> using namespace std;  int main() {   int number=33;   stringstream strs;   strs << number;   string temp_str = strs.str();   char* char_type = (char*) temp_str.c_str(); } 

But is there any method with less typing ?

like image 330
rsk82 Avatar asked Jun 01 '12 08:06

rsk82


People also ask

How do I convert an int to a char?

We can also convert int to char in Java by adding the character '0' to the integer data type. This converts the number into its ASCII value, which after typecasting gives the required character.

How do I convert an int to a char in c?

A char in C is already a number (the character's ASCII code), no conversion required. If you want to convert a digit to the corresponding character, you can simply add '0': c = i +'0'; The '0' is a character in the ASCll table.

How do you convert int to char in Java?

We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.

How do you convert int to char in Python?

Python's built-in function chr() returns a sunicode character equivalent of an integer between 0 to 0x10ffff.


1 Answers

  • In C++17, use std::to_chars as:

    std::array<char, 10> str; std::to_chars(str.data(), str.data() + str.size(), 42); 
  • In C++11, use std::to_string as:

    std::string s = std::to_string(number); char const *pchar = s.c_str();  //use char const* as target type 
  • And in C++03, what you're doing is just fine, except use const as:

    char const* pchar = temp_str.c_str(); //dont use cast 
like image 160
Nawaz Avatar answered Sep 21 '22 17:09

Nawaz