composing a filename using an int variable

I would like to create a file to be written to, using a given number inside the filename (something like output4.txt)

I have:

int function_name (... int node)
...
myfile.open ("output ", node, ".txt");
...

which does not work. Any ideas?

I also tried:
myfile.open("output %d", node);
string file = ("output ", node, ".txt"); --> myfile.open(file);

with:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

Thanks.
Last edited on
I would create a string holding the first part of the filename ("output"), read user input, then append() that onto the string. After that, append() your extension then use c_str() as to get the C-style string for the filename.

1
2
3
4
5
string str("output");
// get input
str.append(the_input); // assuming their input is a string or char*
str.append(my_extension);
myfile.open(str.c_str(), /*...*/);
But the thing he wants is to convert an int to a string. For this the stringstream classes were created:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
  {
  ostringstream filename;
  filename << "output";
  filename << setfill( '0' ) << setw( 3 ) << 42;
  filename << ".txt";

  ofstream f( filename.str().c_str() );
  f << "Hello world!\n";
  f.close();

  cout << "Wrote to \"" << filename.str() << "\"\n";
  return 0;
  }

Hope this helps.
Lol the answer to it all! 42

Cheers!

P.S. sorry for the off-topic burst... couldn't help it :)
'salright.


Would you believe I've never read/seen/heard/imagined any part of The Hitchhikers Guide? :-@
I suspected strongly it was intentional :)

Popular culture is a weird thing... That is even more impressive when possibly different nationalities are in question.

http://en.wikipedia.org/wiki/Answer_to_Life,_the_Universe,_and_Everything#Answer_to_Life.2C_the_Universe.2C_and_Everything_.2842.29


Cheers!
Last edited on
Topic archived. No new replies allowed.