如何使用TEdit(文本框)中的文本编写文件

How to write a File with text from a TEdit(Textbox)

本文关键字:文本 文件 何使用 TEdit      更新时间:2023-10-16

我想寻求一些关于这个小程序的帮助。我正在使用Embarcadero RAD XE2,并试图构建一个带有按钮和文本框的小表单。机制很简单,我在一个文本框中写一些东西,我希望当我点击按钮时,这些东西被写到一个.txt文件中。

这是我的.cpp文件中的代码,格式为:

//---------------------------------------------------------------------------
#include <fmx.h>
#include <iostream.h>
#include <fstream.h>
#include <String>
#pragma hdrstop
#include "STRTEST.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.fmx"
TForm1 *Form1;
//---------------------------------------------------------------------------
int writefile(String A)
{
ofstream myfile;
myfile.open("D://example.txt");
myfile << A;
myfile.close();
return 0;
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
String mystr = Edit1->Text+';';
writefile(mystr);
Form1->Close();
}
//---------------------------------------------------------------------------

现在,我遇到了这个问题:在"mystr<<A;"一行中,我收到了这个错误

[BCC32错误]STREST.cpp(13):E2094'运算符<lt;'未在中实现"UnicodeString"类型的参数的类型为"ofstream"完整分析器上下文STREST.cpp(10):解析:int writefile(UnicodeString)

我不知道该怎么办。如果我用一个直接字符串(即mystr<<"HI")替换A,函数writefile会完美地工作,并用该特定字符串写入文件。

有人知道怎么解决这个问题吗?

String值的<<>>运算符只有在项目中定义了VCL_IOSTREAM时才能实现。即便如此,它仍然不起作用,因为您使用的是ofstream,它不接受Unicode数据(String是CB2009+中UnicodeString的别名)。您必须使用wofstream,然后使用String::c_str()来流式传输值:

//---------------------------------------------------------------------------
#include <fmx.h>
#include <iostream>
#include <fstream>
#include <string>
#pragma hdrstop
#include "STRTEST.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.fmx"
TForm1 *Form1;
//---------------------------------------------------------------------------
int writefile(System::String A)
{
std::wofstream myfile;
myfile.open(L"D://example.txt");
myfile << A.c_str();
myfile.close();
return 0;
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
System::String mystr = Edit1->Text + L";";
writefile(mystr);
Close();
}
//---------------------------------------------------------------------------