Conversions from textbox to string

Hello. I use VC++ 2010 Express. I want to make windows form app. I want to make something like this

1
2
3
4
5
#include <fstream>
...
...
...
ofstream File(vardas->Text + " " + pavarde->Text + ".txt");


And i get this
Form1.h(201): error C2664: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream(const char *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'System::String ^' to 'const char *'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]


I got those textboxes. What conversions do i have to do?
Please write me the exact code.
Can you write that line(s) of code? Please. I don't understand a little.
1
2
3
4
String^ stringFname=vardas->Text + " " + pavarde->Text + ".txt";
char* filename=(char*) Marshal::StringToHGlobalAnsi(stringFname ).ToPointer();
ofstream File(filename);
Marshal::FreeHGlobal(IntPtr(filename));
Should i include something? Because i get:

1>PATH TO PROGRAM\Form1.h(199): error C2653: 'Marshal' : is not a class or namespace name
1>PATH TO PROGRAM\Form1.h(199): error C2228: left of '.ToPointer' must have class/struct/union
1>          type is ''unknown-type''
1>PATH TO PROGRAM\Form1.h(199): error C3861: 'StringToHGlobalAnsi': identifier not found
1>PATH TO PROGRAM\Form1.h(200): error C2065: 'ofstream' : undeclared identifier
1>PATH TO PROGRAM\Form1.h(200): error C2146: syntax error : missing ';' before identifier 'File'
1>PATH TO PROGRAM\Form1.h(200): error C3861: 'File': identifier not found
1>PATH TO PROGRAM\Form1.h(201): error C2653: 'Marshal' : is not a class or namespace name
1>PATH TO PROGRAM\Form1.h(201): error C3861: 'FreeHGlobal': identifier not found
It's not an additional include you need here, it's another using statement (for another .NET namespace.)

When you working with managed code you've got to (a) add the required assembly reference, if not already added, and (b) add a using statement, i.e. (in this case)

using System::Runtime::InteropServices;

But rather than switching between C++/CLI and C++, you could use the .NET way of reading and writing files?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
String^ filename = textBox1->Text + L"\\" + textBox2->Text + L".txt";

StreamWriter^ sw = gcnew StreamWriter(filename);
for(int i = 1; i <= 10; ++i)
	sw->WriteLine("Line #" + i.ToString());
sw->Close();

StreamReader^ sr = gcnew StreamReader(filename);
String^ str = nullptr;
int count = 0;
while ((str = sr->ReadLine()) != nullptr) {
	++count;
}
sr->Close();

textBox3->Text  = count.ToString();


Andy

How to: Write a Text File (C++/CLI)
http://msdn.microsoft.com/en-us/library/vstudio/19czdak8.aspx

How to: Read a Text File (C++/CLI)
http://msdn.microsoft.com/en-us/library/vstudio/y52yxde8.aspx

Last edited on
Topic archived. No new replies allowed.