Adding Vars

Started by
3 comments, last by Xai 18 years, 5 months ago
I currently have a variable like so: const char* image="image.ppm"; i would like to add a var into there eiher an int or a string somthing like this: int frame = 0; while (frame = frame) { frame++; const char* image="image" << frame << ".ppm"; } is there a way to do it so it still a const char*?
Advertisement
Not really. Since this looks like C++, consider using std::string instead of const char *s. If you need to turn a std::string into a const char *, there's always the c_str() member function.
if your making the char const it cannot be redefined in the program.


try using strcat to add

strcat(image, "extra text to add on the end of image)
you get the picture, i must hurry sorry i cannot tell you more
Quote:Original post by Nyte_Falcon
I currently have a variable like so:

const char* image="image.ppm";

i would like to add a var into there eiher an int or a string somthing like this:

int frame = 0;
while (frame = frame) {
frame++;
const char* image="image" << frame << ".ppm";
}

is there a way to do it so it still a const char*?


Not const, no. After all, you're changing stuff at runtime, which is against the definition of const. And at that point, using char* to hold text becomes a bad idea. However, you have a good instinct for the syntax there. The standard library provides a class that will do what you want:

#include <string>#include <sstream>for (int frame = 0; frame < NUM_FRAMES; ++frame) {  stringstream ss;  ss << "image" << frame << ".ppm";  // If we need to hold on to the string data for some other purpose:  string filename = ss.str();  // and then to get the char* we need to open an ifstream:  ifstream picture(filename.c_str());  // Of course, we don't need a temporary if all we're going to do is feed it  // to an ifstream constructor:  // ifstream picture2(ss.str().c_str());}
you may be unaware that a variable does NOT need to be const to be passed to a function that requires a const parameter ...

a "const" constraint on a parameter is not a restriction on what can be passed to the function, it is a restriction on what can be done INSIDE of the function, to the variable ... so if you are trying to modify a const char paramter ... that's a BIG no no ... and you are missing the whole point. But if you are trying to declare a const char* so you can pass it to a function which takes a const char * ... then instead just declare it a char * ... modify it ... then pass it to the function ... all will work.

This topic is closed to new replies.

Advertisement