Vico Pelaez
Vico Pelaez

Reputation: 51

convert int to char* to print

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.

Upvotes: 2

Views: 11344

Answers (3)

juanchopanza
juanchopanza

Reputation: 227468

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();

Upvotes: 5

Loki Astari
Loki Astari

Reputation: 264571

Use this:

std::stringstream val;

val << number;

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

Upvotes: 4

Scooter
Scooter

Reputation: 7059

   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

Upvotes: 1

Related Questions