ofsteam file name from string

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
#include<time.h>
#include<iostream>
#include<fstream>
#include<string.h>

using namespace std;

int main()
{
    string a;
    int i;
	char date[9];
	_strdate(date);
	cout << date << endl;
        for (i=0;i<8;i++){
            a=a+date[i];
        }
    cout << a << endl;
    a=a+".txt";
    cout << a << endl;
    ofstream myfile;
      myfile.open(a); //error: no matching funtion for call to.....
      myfile << a ; //just a test i will change this later when this works
      myfile.close();

	return 0;
}


i'm desperatly trying to create a txt file with the current date but an unexpected error ocured

could somebody tell me why this happend or fix it?
The "open" function takes a c-string, not a string. instead of open(a), do open(a.c_str()).
using the / in a file name doesn't look like it will work.

Updated your code, hope you like it.

output will be changed from 11/28/2012 to 11282012.txt

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
33
34
35
36
37
38
39
40
#include<time.h>
#include<iostream>
#include<fstream>
#include<string.h>

using namespace std;


int main()
{
    string a;
    int i;
	char date[9];
	_strdate(date);
	cout << date << endl;
        for (i=0;i<8;i++){
            a=a+date[i];
        }

    cout << a.size() << endl;
    if (a.size()==8)
    {
    a.erase(2,1);
    a.erase(4,1);
    }
    else
    {cout << "Date String incorrect length" << endl;}
    
    cout << a << endl;
    a=a+".txt";
    cout << a << endl;
    ofstream myfile;
    myfile.open(a.c_str());
//      myfile.open(a); //error: no matching funtion for call to.....
      myfile << a ; //just a test i will change this later when this works
      myfile.close();

	return 0;
}
As SamuelAdams said, a / in a file name cab cause a problem. That's because it's the way you divide the folder name(s) from the file name (Win32 treats both \ and / the same way). So "11/28/2012.txt" is a file called 2012.txt in a folder 28 which is in another folder called 11. If the folders 11 and 28 don't already exist, ofstream will fail when you try to open the file (1012.txt).

By the way

1
2
3
4
5
6
	char date[9];
	_strdate(date);
	cout << date << endl;
        for (i=0;i<8;i++){
            a=a+date[i];
        }


can be recoded as

1
2
3
4
	char date[9];
	_strdate(date);
	a = date;
        cout << date << endl;


and maybe replacing the / by _ or - would result in a more readable file name?

11_28_2012.txt

Either using a for loop or std::replace()

1
2
3
4
5
6
7
// etc
#include <algorithm>
using namespace std;

// etc

replace(a.begin(), a.end(), '/', '_');


Andy


Last edited on
Topic archived. No new replies allowed.