Sign in to follow this  

from int to string

This topic is 4745 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Assuming your talking about C++ you can use string streams to parse to & from strings in memory, e.g.:


#include <algorithm>
#include <iterator>
#include <vector>
#include <sstream>
#include <iostream>

int main() {

std::istringstream iss("123123 4534 656456 6757 5345 23423");

std::vector<int> v((std::istream_iterator<int>(iss)),
std::istream_iterator<int>());

std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ", "));


}

Share this post


Link to post
Share on other sites
Quote:
Original post by Joshnathan
wow, that seems complicated, isn't there an easier way to go around it?


its not complicated at all, its actually very elegant but anyways:


#include <sstream>
#include <iostream>

int main() {

std::istringstream iss("2342");

int i = 0;

iss >> i;

std::cout << i << std::endl;

}


The reason why i didn't show this in the first place was i wanted to show whats possible (something with some meat) and not just the above.

Share this post


Link to post
Share on other sites
Quote:
Original post by Joshnathan
I would like to go from int to string not the other way around, how to? :D



#include <string>
#include <sstream>
#include <iostream>

int main() {

const int i = 343243;
const float j = 4354.5f;

std::ostringstream iss;

iss << "an int:" << i << ", a float: " << j << ", a double: " << 3.4;

std::string s = iss.str();

std::cout << s << std::endl; //or std::cout << iss.str() << std::endl;

}

Share this post


Link to post
Share on other sites
You can write your own utility function called toString and reuse it whenever you need to. I'll show you the specific version for converting integers to strings and then generalise it for any type which supports the << ostream operator.


//toString.h

#include <sstream>

std::string ToString(int n) {
std::stringstream ss;
ss << n;
return ss.str();
}



The general version makes use of templates, so you write it for a general type, whether that's an int, double, std::complex, MyClass type, whatever and it works:

//toString.h

#include <sstream>

template<typename T>
std::string ToString(const T& t) {
std::stringstream ss;
ss << t;
return ss.str();
}


I made ToString take a constant reference as it is generally more efficient to pass objects by reference than by value (although for built-in types like int and doubles its not going to be any more or less efficient).

Usage:

#include <string>
#include <complex>
#include "ToString.h"

int main() {
std::string n = ToString(5);
std::string f = ToString(5.555f);
std::string d = ToString(5.566745235);
std::string c = ToString(std::complex<double>(1.2, 5.6));
return 0;
}

Share this post


Link to post
Share on other sites
Quote:
Original post by Rob Loach
Quote:
Original post by petewood
..."String Goodness"...

That's a good one.


You can also do the other direction - ToInt, or generalised ToType:


//ToType.h
template<typename T>
T ToType(const std::string& s) {
std::stringstream ss;
ss << s;

T result;
ss >> result;
return result
}



Usage:

#include <complex>#include "ToType.h"

int main() {
int n = ToType<int>("1812");
double d = ToType<double>("3.1412");
std::complex<double> c = ToType<std::complex>("(1.2, 3.7)");
return 0;
}




The only problem with this is if you convert a string into a string (heh, we all make mistakes... or maybe with generic code you wouldn't know what you were going to pass to the function). If the string contains spaces it will get broken up at the first space and you'll lose the rest of it. So you need to provide a specialisation, or an overload, just for strings. In it you just return a copy of the string that was passed to the function:


//ToType.h

//...previous code

std::string ToType<std::string>(const std::string& s) {
return s;
}




All of this has already been done better in the boost library lexical_cast

Share this post


Link to post
Share on other sites
Quote:
Original post by petewood
You can write your own utility function called toString and reuse it whenever you need to. I'll show you the specific version for converting integers to strings and then generalise it for any type which supports the << ostream operator.

*** Source Snippet Removed ***

The general version makes use of templates, so you write it for a general type, whether that's an int, double, std::complex, MyClass type, whatever and it works:
*** Source Snippet Removed ***
I made ToString take a constant reference as it is generally more efficient to pass objects by reference than by value (although for built-in types like int and doubles its not going to be any more or less efficient).

Usage:
*** Source Snippet Removed ***


THIS IS PRETTY COOL!!!

Share this post


Link to post
Share on other sites
and to do the same for transformation in char?
here is the problem I have:
I want to use SFont() to print the score of 2 players, but SFont asks for a constant char. I thought a string would be ok, but it wasn't. I want to do something like this:
SFont_Write(screen, font, x, y, score.ToConstChar(score.PlayerScore))

Any idea how?

Share this post


Link to post
Share on other sites
Quote:
Original post by Joshnathan
and to do the same for transformation in char?
here is the problem I have:
I want to use SFont() to print the score of 2 players, but SFont asks for a constant char. I thought a string would be ok, but it wasn't. I want to do something like this:
SFont_Write(screen, font, x, y, score.ToConstChar(score.PlayerScore))

Any idea how?


can't you use a string and call the c_str() method?

Share this post


Link to post
Share on other sites
std::string has a function which returns a const char* version of its contents:

std::string playerScore= ToString(score.PlayerScore);
SFont_Write(screen, font, x, y, playerScore.c_str());


Share this post


Link to post
Share on other sites
there is a function that defined in some compilers, itoa
in the radix parameter, you probably looking for a decimal. its radix=10.
just include stdlib.h

or as the annonymous said, sprintf. it is also a good choose. (include stdio.h)

pex.

Share this post


Link to post
Share on other sites
I now have this function:

void DrawScore()
{
SFont_Font* font;
font = SFont_InitFont(IMG_Load("24P_Copperplate_Blue.png"));
if(!font)
cout << "error initiating font...\n";

string playerscore = score.ToString(score.PlayerScore);
SFont_Write(screen, font, 200, 100, playerscore.c_str());
}


which does... nothing.

I call it here :

void NewGame()
{
SDL_FillRect(screen, NULL, 0);

SDL_Surface *paddle1, *paddle2;
paddle1 = IMG_Load("paddle.bmp");
paddle2 = IMG_Load("paddle.bmp");
int r = 255;
int g = 0;
int b = 255;
SDL_SetColorKey(paddle1, SDL_SRCCOLORKEY, SDL_MapRGB(paddle1->format, r, g, b));
SDL_SetColorKey(paddle2, SDL_SRCCOLORKEY, SDL_MapRGB(paddle2->format, r, g, b));

Paddle1.startx = 20;
Paddle2.startx = 750;
Paddle1.starty = 250;
Paddle2.starty = 250;
Paddle1.x = 20;
Paddle1.y = 250;
Paddle2.x = 750;
Paddle2.y = 250;
score.PlayerScore = 17291;

background = IMG_Load("background/space.jpg");
SDL_Rect back;
back.x = 0;
back.y = 0;
SDL_BlitSurface(background, NULL, screen, &back);
DrawPaddles(paddle1, paddle2, Paddle1.startx, Paddle1.starty, Paddle2.startx, Paddle2.starty);
InitiateBall(screen);
DrawScore();
SDL_Flip(screen);

bool GameOver = false;

while(!GameOver)
{
SDL_Event event;

while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
GameOver = true;
running = false;
break;
case SDL_KEYDOWN:
bool keyup = false;
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
GameOver = true;
break;
case SDLK_UP:
while(!keyup)
{
SDL_Event event;
if((Paddle1.y - 10) > 0)
Paddle1.y-=10;
else
Paddle1.y = 0;


SDL_BlitSurface(background, NULL, screen, &back);
MoveBall();
DrawBall(screen, ball.x, ball.y);
DrawPaddles(paddle1, paddle2, Paddle1.x, Paddle1.y, Paddle2.x, Paddle2.y);
DrawScore();
SDL_Flip(screen);

while(SDL_PollEvent(&event))
{
if(event.type == SDL_KEYUP)
{
keyup = true;
}
}
}
keyup = false;
break;
case SDLK_DOWN:

while(!keyup)
{
SDL_Event event;
if((Paddle1.y + paddle1->h + 10) < screen->h)
Paddle1.y+=10;
else
Paddle1.y = screen->h-paddle1->h;

SDL_BlitSurface(background, NULL, screen, &back);
MoveBall();
DrawBall(screen, ball.x, ball.y);
DrawPaddles(paddle1, paddle2, Paddle1.x, Paddle1.y, Paddle2.x, Paddle2.y);
SDL_Flip(screen);

while(SDL_PollEvent(&event))
{
if(event.type == SDL_KEYUP)
{
keyup = true;
}
}
}
keyup = false;
break;
}
break;
}
}
MoveBall();
DrawBall(screen, ball.x, ball.y);
SDL_Flip(screen);
}
}


Anyone have an idea why it won't draw my score to the screen?

Share this post


Link to post
Share on other sites
Quote:
Original post by snk_kid

std::vector<int> v((std::istream_iterator<int>(iss)),
std::istream_iterator<int>());


What a vexing parse! :)

Share this post


Link to post
Share on other sites
Quote:
Original post by Joshnathan
Anyone have an idea why it won't draw my score to the screen?


Is it at all possible that it is drawing it to the screen but just in the same color as the background? I hate when that happens. Just a thought.

Share this post


Link to post
Share on other sites

This topic is 4745 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this