Mac C++ ???

DelisleBA.info

macrumors member
Original poster
Apr 12, 2011
38
0
Athens, OH
/*
Hey internet,
I am trying to write a program that adds a number to the end of a filename.
*/

Code:
#include <ostream>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    int dayNum = 0;          // Day number.
    string filenameString; // Holder for sequential filename suffix.
    ostringstream convert; // Holder for int daynum to string conversion.
    
    string repFilename = "FILENAME"; //f Name of File.
     
    cout << endl;
    cout << "Day Number: "; // Get the day number.
    cin >> dayNum;
    
    cout << endl;
    
    convert << dayNum; // Assing dayNum to covert.
    
    filenameString = convert.str();  // Change dayNum from int to string.
    
    filenameString = "_DAY_" + filenameString;
    // Add "_day_" to dayNum suffix.
    
    filenameString = repFilename + filenameString + ".txt";
    // Add file name + dayNum suffix.
    
    cout <<"\n";
    cout << "File name is = " << filenameString; // TEST 1
    cout <<"\n";
    
    // TEST 2. should make filename = FILENAME_DAY_2.txt.
    
    dayNum++; // Assign dayNum + 1 to covert.
    
    convert << dayNum; // Assing dayNum to covert.
    
    filenameString = convert.str(); // Change dayNum from int to string.
    
    filenameString = "_day_" + filenameString;
    // Add "_day_" to dayNum suffix.
    
    filenameString = repFilename + filenameString + ".txt";
    // Add file name + dayNum suffix.
    
    cout <<"\n";
    cout << "NEW File name is = " << filenameString.c_str(); // TEST
    cout <<"\n";
    cout <<"\n";

    // but the file name is = FILENAME_day_12.txt
    
} // END main.
// the first pass works great the second pass does not
 

ArtOfWarfare

macrumors G3
Nov 26, 2007
8,565
3,978
I would suggest using breakpoints to inspect each variable along the way, but just looking at your code, I think I see your issue:

You have a line of code that looks like this twice:

Code:
convert << dayNum;
The first time, convert starts empty and is passed "1", so it becomes "1".

The second time, convert starts "1" and is passed "2", so it becomes "12".

That's my guess. I would suggest clearing (flushing?) convert after you're done using it the first time. (C++ isn't my strongest language...)
 

Ap0ks

macrumors 6502
Aug 12, 2008
307
58
Cambridge, UK
As ArtOfWarfare suggested you need to clear the contents of the convert object before you reuse it.

A simple:
Code:
convert.str("");
should suffice.