写入文件内容为何为乱码

steven216 2007-02-05 09:49:08
#include<map>
#include<string>
#include<iostream>
#include<cstring>
#include<set>
#include<fstream>
#include<algorithm>
#include<iterator>

using namespace std;
set<char*>Word;

//按给定的标点来拆分单词
void SplitString(const string&str)
{
size_t nlen = str.length();
char *strDest = new char[nlen + 1];
strcpy(strDest,str.c_str());
char *flag =",.!:<>?";

char *p = strtok(strDest,flag);
while(p)
{
//cout<<p<<"\n";
Word.insert(p);
//ofs<<p<<"\n";
p = strtok(NULL,flag);
}
delete[]strDest;
}

int _tmain(int argc, _TCHAR* argv[])
{

ifstream ifs("c:\\Music.txt");

if (!ifs.is_open())
{
cout<<"open file failed\n";
return 0;
}

istream_iterator<string>ii(ifs);
istream_iterator<string>eof;
for_each(ii,eof,SplitString);

//将文件中分离的单词写入到文件中
ofstream ofs("c:\\word.txt",ios_base::app);
if (!ofs.is_open())
{
cout<<"open file failed\n";
return 0;
}
ostream_iterator<string>oo(ofs,"\n");
copy(Word.begin(),Word.end(),oo); //为何写入文件中的单词为乱码?

ifs.close();
ofs.close();
system("pause");
return 0;
}

//开发环境 vs2005, XP sp2
//写入文件中的结果 用其它文本文件打开也是乱码
//O:
//:
//?
//饾:
//萚:
//饾:
//O:

//copy 是否像下面这个样子呢?
//template<class T, class U>
//void copy(T first, T last, U out)
//{
// while (first != last)
// {
// *out++=*first++;
// }
//}
...全文
394 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
jixingzhong 2007-02-06
  • 打赏
  • 举报
回复


其实如果是这样的问题,
可以单步程序查看需要写入文件的变量的值就可以发现问题了 ~
steven216 2007-02-05
  • 打赏
  • 举报
回复
明白了,感谢a_b_c_abc11(◥ @^@◤业余爱好而已)
a_b_c_abc11 2007-02-05
  • 打赏
  • 举报
回复
void SplitString(const string&str)
{
......
//delete[]strDest; 你在这里把插入set<char*>Word;的字串删除了,到你写入文件的时后自然写入一些无效数据.
经测试,注释了这句,得到正常可读文件.
}
weally 2007-02-05
  • 打赏
  • 举报
回复
是否是ASCII/UNICODE编码的问题?Unicode编码的文件前两个字节应写入0xFEFF

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧