Variable Number in File Name

I'm trying to make multiple files with results from some tests I'm running. The problem is, I can't make my variable a part of the string for the text file name.

If "PID_Exceltest 1" is already there, it should make "PID_Exceltest 2" and so forth. Right now, all it does is an endless "cout" loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream> 
#include<fstream>
#include <Windows.h>
#include <stdio.h>
using namespace std;
int main()
{
	char oldname[] ="PID_Exceltest.txt";
	ofstream ExFile	(oldname, ios::app | ios::ate);
	if (ExFile.is_open()) // Makes sure the original file's there.
	{
		ExFile.close();
		int filename_num = 1;
		goback:
		char newname[] ="PID_Exceltest 1.txt";
		// Instead of "PID_Exceltest 1.txt" it should take up the
                // number of "filename_num" so it can be any number.
		
		ifstream ExFile2 (newname);
		if (ExFile2) // Checking for existence of
                             //another file of same name.
		{
			ExFile2.close();
			filename_num++;	// Increases the number
                                        //of the file name.
			cout << "Rename!" << filename_num << endl;
			goto goback;
		}
		else
		{rename( oldname , newname );} // Renames the file.
	}
}
Use a stringstream to put numbers into strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    stringstream ss;
    int num;

    cout << "Enter a number: ";
    cin >> num;

    ss << "PID_ExelTest ";
    ss << num;

    cout << ss.str() << endl;

    return 0;
}


More information: http://cplusplus.com/reference/iostream/stringstream/
I can't seem to be able to use the str() function as input for "ifstream" and rename (). I think it requires a character or a direct quotation. Is there any way to convert it?
1
2
3
4
5
6
7
8
9
10
// Either:
char oldname = "Something.txt";
char newname = "SomethingElse.txt"; // Needs the quotes.
ifstream Random (newname)
rename (oldname, newname);

// Or

ifstream Random ("newname.txt")
rename ("oldname.txt", "newname.txt");
Try using the c_str() function.

 
ss.str().c_str();


Should work.
I'll try that. But where should I put it? I'll try this first:
 
char newname[] = ss.str().c_str();
That won't work. Just pass it directly to the fstream's constructor or open function.
I just put "newname.str().c_str()" as the input for ifstream and rename(). It works, Thanks! Now one more thing. I'll need to create a folder if one doesn't exist, and store all the files in that folder. If I have any problems, I'll post.
Topic archived. No new replies allowed.