关于fstream的问题

kkwolf1982 2004-11-20 09:40:05
#include<fstream>
#include<iostream>
#include<string>
int main()
{
using namespace std;
//已建立rd.txt在C盘
fstream io("c:\\rd.txt",ios_base::in);
string a,b;
int i;
if(!io)
cerr<<"bad connect!"<<endl;
io.seekg(2);
io>>a;
cout<<a<<endl;
io.seekg(3);
i=io.tellg();
cout<<i<<endl;
if(!io)
cerr<<"bad connect2!"<<endl;
io>>b; //为什么这句好象不起作用一样,各位高手帮忙解答!!
cout<<b<<endl;
system("pause");
return 0;
}
rb.txt中包含字符: abcdefghi
还有我把 fstream io("c:\\rd.txt",ios_base::in);改成 fstream io("c:\\rd.txt",ios_base::in|ios_base::app);就连接不上了,而使用("c:\\rd.txt",ios_base::in|ios_base::out);就可以了,为什么(使用DEVC++)

请解答,谢谢!
...全文
87 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
sasdaa 2004-11-22
  • 打赏
  • 举报
回复
这是因为in 处于“遇到文件结束符的状态”。只要in 处于这种状态,就不能再执行输入和输出操作。解决方案是调用clear() 清除文件的这种状态。
#include<fstream>
#include<iostream>
#include<string>
int main()
{
using namespace std;
//已建立rd.txt在C盘
fstream io("c:\\rd.txt",ios_base::in);
string a,b;
int i;
if(!io)
cerr<<"bad connect!"<<endl;
io.seekg(2);
io>>a;
cout<<a<<endl;
io.seekg(3);
i=io.tellg();
cout<<i<<endl;
if(!io)
cerr<<"bad connect2!"<<endl;
io.clear();//加上这句
io>>b; //为什么这句好象不起作用一样,各位高手帮忙解答!!
cout<<b<<endl;
system("pause");
return 0;
}
kkwolf1982 2004-11-21
  • 打赏
  • 举报
回复
晕,都问了一天了?怎么没人知道吗?。。。
hongjun_han 2004-11-20
  • 打赏
  • 举报
回复

#include<fstream>

int main()
{
using namespace std;
//已建立rd.txt在C盘
fstream io("c:\\rd.txt",ios_base::in);
string a,b;
int i;
if(!io)
cerr<<"bad connect!"<<endl;
io.seekg(2);
io>>a;
cout<<"a is " << a <<endl;
cout <<"-------------------------------"<< endl;
io.seekg(3);
i=io.tellg();
cout<<i<<endl;
cout <<"**************************************"<< endl;
if(!io)
cerr<<"bad connect2!"<<endl;
io>>b; //为什么这句好象不起作用一样,老大帮忙解答!!
cout<<b<<endl;
cout <<"======================================"<< endl;
system("pause");
return 0;
}

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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