请教个关于to string的问题

tommy851027 2006-04-15 11:39:29
//程序1。正确。

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main()
{

ofstream outfile("test.txt");
outfile<<"abcdefg"<<" "; //向文件中写入内容
outfile.close();
ifstream infile("test.txt");
ostringstream into_string;
char ch;
while(into_string && infile.get(ch))
into_string.put(ch);
infile.close();
string str1;
str1 = into_string.str();
//成员函数str()返回与ostringstream类对象相关联的string对象
cout<<str1<<endl;
system("pause");
return 0;
}

程序2如下:
为何程序2没有建立test.txt文件?就算我手工建立了,最后输出的内容也不是abcdefg 啊。
程序1和程序2有什么不同呢,我觉得没什么不同啊,就是把输入输出写成一个io对象了啊。
请教了。


#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main()
{

fstream io("test.txt",ios::in|ios::out);
io<<"abcdefg"<<" "; //向文件中写入内容
ostringstream into_string;
char ch;
while(into_string && io.get(ch))
into_string.put(ch);
io.close();
string str1;
str1 = into_string.str();
//成员函数str()返回与ostringstream类对象相关联的string对象
cout<<str1<<endl;
system("pause");
return 0;
}
...全文
161 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
mhisky 2006-05-10
  • 打赏
  • 举报
回复
mark
sharpdew 2006-04-16
  • 打赏
  • 举报
回复
对于fstream类,不要随便在读写操作之间尽心转化,如果一定需要转化的话,必须进行一个seek的操作,到达当前位置,在转化读写属性。否则,结果不可预期。
重复一下,我测试的程序如下:
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
fstream io("test.txt",ios::in|ios::out|ios::trunc);
io << "abcdefg" ;

// 下面这句话是一定要的!
//cout << io.tellp() << endl;
io.seekp(0, ios_base::beg);
//cout << io.tellp() << endl;

ostringstream into_string;
char ch;
while(into_string && io.get(ch))
into_string.put(ch);
io.close();

string str1;
str1 = into_string.str();

cout<<"Text:"<<str1<<endl;

return 0;
}
sharpdew 2006-04-16
  • 打赏
  • 举报
回复
fstream io("test.txt",ios::in|ios::out|ios::trunc); // ---- 这里要加上trunc标记!
io << "abcdefg" ;

//cout << io.tellp() << endl;
io.seekp(0, ios_base::beg); // ---- 这句话是一定要的!
//cout << io.tellp() << endl;

ostringstream into_string;
char ch;
while(into_string && io.get(ch))
into_string.put(ch);
io.close();

string str1;
str1 = into_string.str();

cout<<"Text:"<<str1<<endl;
beijixuexiong 2006-04-16
  • 打赏
  • 举报
回复
是刷新缓冲,但是之前我也遇到过类似的问题,似乎是io里要到一定的数量才写进文件,相信如果在io<<"abcdefg"<<" ";之后加上io.close()它就可以写进去的,但是上次我遇到的时候加了一个io.flush()就可以了,它就可以写进去了~

LZ不妨试一下~
xyjchinese 2006-04-16
  • 打赏
  • 举报
回复
楼上的那个只是刷新缓冲区吧。不起作用。
beijixuexiong 2006-04-15
  • 打赏
  • 举报
回复
io<<"abcdefg"<<" ";
---------
之后加一句
io.flush()
试试
tommy851027 2006-04-15
  • 打赏
  • 举报
回复
io.flush()
什么意思?

64,643

社区成员

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

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