在MFC中这样操作文件怎么不对?

yoyota 2006-04-29 06:02:56
我想实现的是:把数组 m_hist里面的浮点数据逐个读到文件中,以方便检查数据的正确性!
相应的代码如下:

#include <fstream>
..........
..........
ofstream outfile("hist",ios_base::out);
if(!outfile)
{
cerr<<"can't open file"<<endl;
exit(-1);
}
else
{
for (i=0; i<256; i++)
{
if( (i%16) == 0)
{
outfile<<endl;
outfile<<m_hist[i]<<", ";
}
else
{
outfile<<m_hist[i]<<", ";
}
}
}
结果编译出错,说ofstream不认识,明明是定义了头文件的,是不是MFC里面不能这样用?

现改用CFile文件类:
代码如下:
CFile mfile;
mfile.Open("hist.txt",CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite);
CArchive ar( &mfile, CArchive::store );
CString str;
for (i=0; i<256; i++)
{
if( (i%16) == 0)
{
ar<<"\n";
ar<<m_hist[i]<<",";
}
else
{
ar<<str<<",";
}
}

ar.Close();
mfile.Close();
打开文本文件 hist.txt, 发现诸如"\n"换行,“,”逗号这些都变成小方块了,ms不认识,另外,如果我在打开模式中加入 CFile::typetext 这一项,编译也通不过,不知为何?
关于文件读写的问题始终有很多不清楚的地方,还望各位点拨迷津!
...全文
121 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xhzxlqt 2006-05-01
  • 打赏
  • 举报
回复
你的系统或VC有问题
我给你的代码,我是测试通过的,并且打开生成的文件看过,没有问题.
cppseekey 2006-04-29
  • 打赏
  • 举报
回复
(2) 用<fstream>, using namespace std 可以, 但碰到 cerr 出错,提示undeclared identifier;
对于这个需要
#include <iostream>
yoyota 2006-04-29
  • 打赏
  • 举报
回复
首先谢谢各位!
碰到的问题如下:
(1) 改成<fstream.h>,找不到这个头文件
(2) 用<fstream>, using namespace std 可以, 但碰到 cerr 出错,提示undeclared identifier;
(3) CFile中CFile::typeText一加上还是出错。
(4) 把 "\n"=>"\r\n",输出仍然是乱码,不是换行。
DentistryDoctor 2006-04-29
  • 打赏
  • 举报
回复
"\n"=>"\r\n"
xhzxlqt 2006-04-29
  • 打赏
  • 举报
回复
#include <fstream.h>//这儿你少了.h

.........
void COfstreamDlg::OnButton1()
{
// TODO: Add your control notification handler code here
float m_hist[256];
for (int j=1; j<257; j++)
{
m_hist[j]=(float)rand()/(j*1.2);
}
ofstream outfile("F:\\vcuser\\Ofstream\\Debug\\hist",ios::out);//这儿需要改为ios::
if(!outfile)
{
cerr<<"can't open file"<<endl;
exit(-1);
}
else
{
for (int i=0; i<256; i++)
{
if( (i%8) == 0)
{
outfile<<endl;
outfile<<m_hist[i]<<", ";
}
else
{
outfile<<m_hist[i]<<", ";
}
}
}

}
handsomerun 2006-04-29
  • 打赏
  • 举报
回复
用CFile的话

CFile::typeText
T大写
handsomerun 2006-04-29
  • 打赏
  • 举报
回复
如果是
#include <fstream>

那么还要加
using namespace std;
handsomerun 2006-04-29
  • 打赏
  • 举报
回复
#include <fstream.h>

ofstream outfile("hist",ios_base::out);

=>

ofstream outfile("hist",ios::out);
yoyota 2006-04-29
  • 打赏
  • 举报
回复
上面代码没贴好,再贴一次

ofstream outfile("hist",ios_base::out);
if(!outfile)
{
cerr<<"can't open file"<<endl;
exit(-1);
}
else
{
for (i=0; i<256; i++)
{
if( (i%16) == 0)
{
outfile<<endl;
outfile<<m_hist[i]<<", ";
}
else
{
outfile<<m_hist[i]<<", ";
}
}
}

16,548

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • AIGC Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

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