Skip to main content
gamedev.net
🔒 Locked

type convertion problem

Started by Yashin Jun 13, 2006 at 3:24 AM 5 replies 600+ views
Original Post
Yashin
Yashin
Hello everyone. I have a problem. I need to load a series of images which are named from "1.pgm" to "128.pgm" in c++; I am trying to use a for loop and concatenate the loop index with ".pgm". But strcat takes two characters. How do i convert the integer into char??
Red Ant
Red Ant
In C, I'd use sprintf.

char myBuffer[ 200 ] = { 0 };for ( int myInt = 1; myInt  <= 128; ++myInt ){     sprintf( myBuffer, "%i.pgm", myInt );        // Do something with the name that you just wrote to myBuffer.    // ...}



P.S. Using snprintf() is probably safer because it passes the size of the buffer to the function as well. This prevents buffer overruns.

2nd P.S Since you said you're coding in C++ ...

#include <sstream>void func(){    for ( int i = 1; i <= 128; ++i )    {        std::ostringstream myStream;        myStream << i << ".pgm";        // Call myStream.str() to get the string.    }}
Yashin
Yashin
thanks a lot for the help!!
Yashin
Yashin
Hi again, am still getting some troubles

void func()
{
for ( int i = 1; i <= 128; ++i )
{
std::ostringstream myStream;
myStream <<"images/"<< i << ".pgm";


}
}

when am displaying it through cout<

ifstream indata;
indata.open(myStream.str());

i could have stored it in a string first like

char temp[10];
strcpy(temp,myStream.str());


but its unable to copy the string(probably because its not a string) into temp;but i need to use it with indata.open()
Any other alternatives?
Enigma
Enigma
std::ifstream indata(myStream.str().c_str());

The str() member function of a stringstream returns a std::string, but the std::ifstream constructor requires a const char *. Use the c_str() member function of std::string to obtain a const char * to the contained string data.

Σnigma
Zakwayda
Zakwayda
You're probably looking for the std::string member function c_str().

[Edit: never mind.]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.