creating dynamical output file names

This is a discussion on creating dynamical output file names within the C++ Programming forums, part of the General Programming Boards category; I'm trying to write to output files that have dynamically created names. I can do this (I think) by using ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    44

    creating dynamical output file names

    I'm trying to write to output files that have dynamically created names. I can do this (I think) by using an ostringstream variable, but the file variable expects a pointer to a constant char. How do I convert this ostringstream variable (called 'result' here) to a pointer to a constant char? 'r' is an integer here. I tried converting the ostringstream variable to a string variable, but the ofstream variable won't accept that either. This is the few lines of code that are important:

    Code:
    result << "testfiles_" << r;
    std::string bufoutput_s = result.str();
    ofstream outputfile (bufoutput_s);

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    266
    ostringstream can be converted to a string by mean of str() , and a string can be converted to a c style string by c_str()

    Code:
    result << "testfiles_" << r;
    ofstream outputfile (result.str().c_str());

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    44
    awesome, that works. I didn't know it was possible to use a member function of a member function. Thanks.

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    It's not a member function of a member function. The str() member function return's a std::string object in this case a temporary string object that then has it's c_str() member called. It just happens to all be on one line and looks like the chaining concept seen so often in the use of the stream insertion/extraction operators (<</>>).
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 09:38 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21