Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 310
  • Last Modified:

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.
0
HHB222002
Asked:
HHB222002
1 Solution
 
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now