Int in filename

#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
   fstream f;
   
   int Number;

   f.open( *FILE PATH HERE* , ios::out);

I want to open a txt document in the c drive called "A__.txt"  (where the "__" is replaced with whatever value Number is).  My question is how I can combine "c:\\A" + Number + ".txt" to put into the file path.
HHB222002Asked:
Who is Participating?
 
lwinkenbCommented:
char szFile[32];
int number = 5;
sprintf(szFile,"c:\\A%i.txt",number);
f.open(szFile,ios::out);
0
 
Sys_ProgCommented:
Use a variable for type char*(say char * str)

Initialise it with the initial string i.e. c:\........

Then using strcat, concatenate the value in Number into it and then concatenate ".txt. to the str

Then use the str in place of the filename in f.open
0
 
bcladdCommented:
Or, in a slightly more C++-ish manner you can use strstream:

#include <string>
#include <strstream>

...

     int Number = /* some value set */;

    strstream convert;
    convert << "A" << Number << ".txt";
 
    string fName;
    convert >> fName;

    // Now use fName as the name of your file and you are golden

-bcl
 
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
bcladdCommented:
Sorry- Forgot

using namespace std;

(or the name of the class is std::strstream)

-bcl
0
 
HHB222002Author Commented:
bcladd-

fName needs to be a char not a string though
0
 
bcladdCommented:
Use the c_str() method to return a pointer at a C-style string containing the information in a std::string:

ifstream input(fName.c_str());

-bcl
0
 
HHB222002Author Commented:
Thanks for your help.

I still can't get bcladd's way to work so I'm giving the points to lwinkenb
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.