【发布时间】:2014-05-23 08:49:00
【问题描述】:
我正在尝试开发一个小型 Windows 应用程序,以提高我在 MFC 框架之外的 C++ 技能并帮助我学习外语。
我想做一个小型的、个人的和易于移植和使用的字典,虽然我在开发 GUI 方面没有任何问题,但我在保存和恢复数据方面确实很痛苦。
我的想法是写下一个结构如下的二进制文件:
int (representing the number of words)
int (representing the string length + \0)
sequence of characters zero-terminated.
现在,我正在学习俄语,我的主要语言是意大利语,所以我不能使用普通的旧 std::string 来写单词,另外,谢谢微软,我正在使用 VS2010 与所有商品和bads随之而来。我正在向您展示我写下 int 和 wstring 的例程://Writing int
void CDizionario::ScriviInt( int nInt, wofstream& file ) const
{
file.write( reinterpret_cast < const wchar_t * > ( &nInt ), sizeof( nInt ) );
file.flush();
}
// Writing string
void CDizionario::ScriviWString( int nLStringa, const wstring* pStrStringa, wofstream& file ) const
{
wchar_t cTerminatore;
string strStringa;
file.write( pStrStringa->c_str(), nLStringa );
file.flush();
cTerminatore = L'\0';
file.write( &cTerminatore, sizeof( wchar_t ) );
file.flush();
}
// Reading int
void CDizionario::LeggiInt( int *pInt, wifstream& file )
{
file.read( reinterpret_cast < wchar_t * >( pInt ), sizeof( int ) );
}
// Reading wstring
void CDizionario::LeggiWString( int nLStringa, wstring& strStringa, wifstream& file )
{
wchar_t *pBuf;
streamsize byteDaLeggere;
byteDaLeggere = nLStringa;
pBuf = new wchar_t[(unsigned int)( byteDaLeggere * sizeof( wchar_t ) )];
file.read( pBuf, byteDaLeggere * sizeof( wchar_t ) );
strStringa.append( pBuf );
delete [] pBuf;
}
// Constructor
CDizionario::CDizionario( void )
{
m_pLoc = new locale( locale::classic(), new codecvt_utf8_utf16 );
}
// Somewhere in my code before calling LeggiInt/ScriviInt/LeggiWString/ScriviWString:
// ...
file.imbue( *m_pLoc );
嗯,我的第一个测试是:ciao - привет,结果:
01 00 ee bc 90 22 05 00 ee bc 90 22 63 69 61 6f
00 ec b3 8c 07 00 ee bc 90 22 d0 bf d1 80 d0 b8
d0 b2 d0 b5 d1 82 00 ec b3 8c
数字被正确读取,当我写下字符串时出现问题:我希望 ciao (63 69 61 6f 00 ec b3 8c) 以 10 个字节(wchar_t 大小)而不是 5 个字节写入,就像俄语翻译一样(d0 bf d1 80 d0 b8 d0 b2 d0 b5 d1 82 00 ec b3 8c)。显然我遗漏了一些东西,但我不知道它是什么。你们能帮帮我吗?另外,如果您知道解决问题的更好方法,我很开放。
编辑:解决方案
按照@JamesKanze 提出的两种方法中的第一种,我决定牺牲一些可移植性,让系统完成我的作业:
void CDizionario::LeggiInt( int *pInt, ifstream& file )
{
file.read( reinterpret_cast( pInt ), sizeof( int ) );
}
void CDizionario::LeggiWString(int nLStringa, wstring& strStringa, ifstream& 文件) { 字符 *pBuf; 流大小字节DaLeggere; wstring_convert> 转换器; byteDaLeggere = nLStringa; pBuf = new char[byteDaLeggere]; file.read(pBuf, byteDaLeggere); strStringa = converter.from_bytes(pBuf); 删除 [] pBuf; }
void CDizionario::ScriviInt(int nInt, ofstream& 文件) const { file.write(reinterpret_cast(&nInt),sizeof(nInt)); 文件.flush(); } void CDizionario::ScriviWString( const wstring* pStrStringa, ofstream& 文件 ) const { 字符终止; 字符串 strStringa; wstring_convert> 转换器; strStringa = converter.to_bytes(pStrStringa->c_str()); ScriviInt(strStringa.length() + 1, 文件); file.write(strStringa.c_str(), strStringa.length()); 文件.flush(); c终止 = '\0'; file.write( &cTerminatore, sizeof( char ) ); 文件.flush(); }
【问题讨论】:
标签: c++ visual-studio-2010 unicode-string wstring