Sign in to follow this  

type convertion problem

This topic is 4204 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

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??

Share this post


Link to post
Share on other sites
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.
}
}



Share this post


Link to post
Share on other sites
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<<myStream.str(), its working fine.. but i need to do


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?

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

This topic is 4204 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