openinig files with sequental filenames

Hello everyone,

I have a whole bunch of bitmap files that are sequentially numbered (0000.bmp, 0001.bmp, 0002.bmp, ect) and i want to open each one successively in my program to extract some data from each one.

There is no actual program right now as I'm just trying to figure out how to get this segment to work properly (the rest is easy stuff). Here is what i have right now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

void main()
{
	using namespace std;

	for (int i = 0; i < 10; i++)
	{
		fstream myBitmap;
		myBitmap.open(*here is where i have a problem*);
		//read bitmap to memory block
		myBitmap.close();
		//do stuff with the bitmap then delete memory block
	}
}


My problem is that the argument for the fstream function, .open(), needs to be some sort of incrementing file name tied to my counter i.

Everything works fine if I hardcode a file name like this: myBitmap.open("test.bmp"); but that's not what i want to do.

I tried converting the counter to a string using stringstream and then concatenating the bits of strings into a complete filename. However, when I throw the variable holding the filename into the argument of .open(), my compiler gets mad at me...

1
2
3
4
5
6
7
8
	

	string test = ".bmp";
	stringstream test2;
	test2 << i;
	string test3 = test2.str();
	test =  test3 + test;


I also tried manually constructing a string using a char array. That gives no compile errors, but the program will not read or write any files I specify (in short, it did nothing!).

I've done the best to my abilities and I'm stumped, please help.
Consider the following code:

 
std::cout << std::setw( 4 ) << std::setfill( '0' ) << 1 << std::endl;


Thanks for the reply,

I apologize in advance...I'm actually very new to c++ and programming in general (approx 1-2 weeks of experience?). (and to make matters worse, I think I have the swine flu and my head currently spinning...but regardless, I must press onwards!)

Well, it took me a little while to figure out whats going on, but ok, now I get it. That would be useful. I suppose I would then use stringstream again to get it into a string...but then what? Last time i stuck a string variable inside that function, the compiler got mad at me (using Visual studio 2008 Professional...because it was free).


edit: Actually I think I'm going to go onto sleep mode for the next little while...uuuggg...
Last edited on
You are correct.

the stream .open() functions take a const char* as parameter, so if you have the name of the file in a std::string, you have to call .c_str() on the string to get a const char*.

Alright, thank you jsmith. It all worked out.
Topic archived. No new replies allowed.