creating "wchar_t" at runtime

why wont this line work?
I am just simply trying to create a wchar_t string at run time but my definition below won't work.

wchar_t * cptrDocname = new wchar_t L"HelloWorld.txt";












full code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
#include <cwchar>
using namespace std;
int main ()
{
	ofstream MyFile;
	wchar_t * cptrDocname = new wchar_t L"HelloWorld.txt";
	//MyFile.open ("HelloWorld.txt"); //Creates a text document called HelloWorld.txt
	MyFile.open (cptrDocname); //Creates a text document called HelloWorld.txt
	MyFile << "Hello World I am a text document :)" << endl; //Writes in HelloWorld.txt
	MyFile.close ();	//Closes the document
	delete cptrDocname;
	cout << "Press ENTER to end the program." << endl;
	cin.get ();
	return 0;
} 


error message:
1>c:\users\home\documents\visual studio 2008\projects\dynamic naming\dynamic naming\main.cpp(8) : error C2143: syntax error : missing ';' before 'string'
If your string is constant, why do you want to allocate memory dynamically?

FYI, the correct way is:

1
2
3
4
5
6
const wchar_t c_s[] = L"HelloWorld.txt";
wchar_t *s = new wchar_t[_countof(c_s)];
wcscpy(s, c_s);
....
delete[] s; //Note the square brackets.
....


If your compiler doesn't understand _countof(), then #define it:

#define _countof(X) (sizeof(X) / sizeof(X[0]))
I want to create a system that allows a user to create and name any document at run time so hence i'm trying the dynamic naming system
thanks in worked
#define _countof(X) (sizeof(X) / sizeof(X[0]))


blech.

Do this instead:

1
2
template <typename T,unsigned S>
inline unsigned countof(const T (&v)[S]) { return S; }
Topic archived. No new replies allowed.