I've got following code section:

#include "stdafx.h"

int main()
{
	string str;
	
	cout << "Enter file name: ";
	
	getline (cin,str,cin.widen('\n'));

	char* file_name=new (nothrow) char[str.length()];

	if(file_name==0)
	{
		cout << "Error: Memory could not be allocated!\n";
	}
	else
	{
		strcpy(file_name,str.c_str());
	
		WriteFile(file_name);		
		ReadFile(file_name);

		delete[] file_name;
	}

	getch();

	return 0;
}

When I insert the red line, my program warms following error:


Please help me explain this error! Thanks!

why did you bother creating that pointer just to pass to a function? All you have to do is pass string's c_str() WriteFile(str.c_str()); >>line #9: cin.widen('\n')
What is that supposed to do -- unless you compile for UNICODE it will do nothing. Seems more reasonable to just do this: getline (cin,str); and let getline() do its job.

where is file header file "stdafx.h" ??? can u post that file code as well... :)

stdafx.h is a standard Microsoft IDE-written header file. Hopefully the op of this thread has added proper STL headers to that file, such as <ifstream>. The program would not compile if that were not the case.

stdafx.h is a standard Microsoft IDE-written header file, and has nothing to do with the problem in this thread. You can just ignore it.

ooooooooh microsoft one..... :)

do
    ignore
done

Its used by M$ compiler to produce pre-compiled headers, which can greatly speed up the compiling process on large multi-file *.cpp projects that all need the same header files. stdafx.h has little if any value on single *.cpp file projects.

Well, you should perhaps try to allocate +1 byte while using new: char* file_name=new (nothrow) char[str.length()+1]; You know why!! don't you?

Thank you very much! I repaired according to Ancient Dragon's idea, and ok! But I still want to know why my code I posted has got error. Can you help me, please?

Hi, defender!
If you want to refer to my project, please contact me by ttqtrang146 (YM). I'll send a email to you.

Thank you very much! I repaired according to Ancient Dragon's idea, and ok! But I still want to know why my code I posted has got error. Can you help me, please?

Explained in post #7 of this thread.

This article has been dead for over six months. Start a new discussion instead.