convert int to char* to print

11,157

Solution 1

If all you want to do is print a number to the screen, then you can stream to std::cout:

#include <iostream>

int nubmer = ....;

std::cout << number;

Otherwise, you can stream the number into an std::ostringstream, and get the underlying const char*:

std::strimgstream o;
o << number;
const char* string_ = o.str().c_str();

Solution 2

Use this:

std::stringstream val;

val << number;

val.str();         // Gets you a C++ std::string
val.str().c_str(); // Gets you a C-String

Solution 3

   char label[100] = {"0"};
   printf("%s\n",label);
   int number = 90;
   sprintf(label,"%d",number);
   printf("%s\n",label);
   sprintf(label,"%d",number + 1);
   printf("%s\n",label);

output:

0
90
91
Share:
11,157
Vico Pelaez
Author by

Vico Pelaez

Updated on June 14, 2022

Comments

  • Vico Pelaez
    Vico Pelaez almost 2 years

    I want an int value to display in screen as a string. This is for a game I am doing in opengl. I have something like this:

    char *string = "0"; // to declare
    
    sprintf (label,"%d" ,string); // This prints 0
    

    This works perfect to print the 0 in the screen, however as you might understand I want the 0 to be changing. I tried converting int to string and trying to assign this to the char *string, but i think it is not possible. I am a newbie in C++ so I do not know much about I would much appreciate your help with this. What I want to achieve is this:

    char *string = "0"; // to declare
    int number = 90; // declare int to be converted;
    
    sprintf (label,"%d" ,string); // This prints 90
    

    I have found converting methods for int to char methods, howevernon have solved my issue. Thank you for all your help in advance.