C++程式 调试运行 出错..seekg和seekp

来源:百度知道 编辑:UC知道 时间:2024/09/20 07:06:49
初学C++语言 第三章 ..胡乱编写的东西...出了点问题..
int main()
{
vector<string> textgroup;
string textfile;
fstream test;
test.open("d:\\test.txt");
if(!test)
cout<<"文件打开出错"<<endl;
for(int n=1;n;)//将文件中的字符 全部按空格分组输入到内存;
{
while(1)
{
if(test.eof()){n=0;break;}
textfile+=test.get();
if(textfile[textfile.size()-1]==' ')break;
}
textgroup.push_back(textfile);
textfile.~string();
}
为何将while(1)改成while(textfile[textfile.size()-1]==' ')执行程序会出错?runtime..........这样的错误...只要放入 无论是 while或者 for中 作为条件 都不行 只能放到 if语句中...

另外还有一个问题 如下程序.
为何要这样写 test.seekg(0,std::ios::beg);test.seekp(0,std::ios::beg);
单独使用 :test.seekp(0,std::ios::beg);
为何达不到 覆盖原来txt 的目的

以下 为 源程序:
#include<fstream>
#include<vector>
#include<iostream>
#include<string>
#define null 0

我来回答楼主所提问题:

1、第一个问题原因是当textfile.size()为0时,代码textfile[textfile.size()-1]执行是不成功的,因为访问了非法的内存空间。
2、第二个问题原因是当test.eof()返回真值时,test的错误标志被设置为eofbit,于是,后续所有针对test的操作都不能得到预期的结果,比如tellp、tellg、seekg、seekp等,因此,在进行其他针对test的操作前,需要清除该错误标志:
test.clear()
3、代码:textfile.~string();隐含了出错的可能,建议修改为:textfile.clear();