读书人

请问读取文本并排除异常数据的有关问题

发布时间: 2012-08-25 10:06:20 作者: rapoo

请教读取文本并排除错误数据的问题
请教各位达人这样一个有选择的读取文本数据并排除其中错误项的问题:

我需要做一个读取文本数据,并显示其中部分数据的程序,其要求如下:

1、程序首先要从文本中获知需要读取多少条数据(每条数据都是由一个字符串和一个数字组成),其中数字项部分超过定值的就打印在屏幕上。
2、其次,如果数据中,某条的数字部分的数据读取发生了错误,则跳过该条,接着显示后面的数据。

我设计的程序只能做到1的要求(如果将标注成注释的代码段恢复企图达到要求2,则编译出错):

C/C++ code
//读取文本并分类显示#include<iostream>#include<fstream>#include<cstdlib>using namespace std;struct mod_donator{    char name[20];    double money;};int main(){    ifstream mFile;    mFile.open("001.txt");    int k=0;    int j=0;    if(!mFile.good())    {        cout<<"Can not open file."<<endl;        exit(EXIT_FAILURE);    }    int size;    if (!(mFile>>size)) //先判定需要读取多少条数据    {        cout<<"Read head data error, program terminating."<<endl;        exit(EXIT_FAILURE);    }        mod_donator *mod=new mod_donator[size];    for(int i=0;i<size;++i)    {        if ((mFile>>mod[i].name) && (mFile>>mod[i].money))        {                ++k;            if (mod[i].money>1000)            {                cout<<"No. "<<i+1<<"\t";                cout<<mod[i].name<<endl;                ++j;            }        }                  //以下部分一编译就出错        /*else        {            mFile.clear();            while (mFile.get()!="\n")            {                continue;            }        }*/    }    delete mod;    mFile.close();    return 0;}


出错信息如下:
error C2446: “!=”: 没有从“const char *”到“int”的转换
error C2040: “!=”: “int”与“const char [2]”的间接寻址级别不同

但是,我在只需要读取一种数据的程序里这样设计却可以成功执行:
C/C++ code
//读取文本并识别错误数据#include<iostream>#include<fstream>#include<cstdlib>const int Size=10;int main(){    using namespace std;    ifstream mFile;    mFile.open("001.txt");    int temp[Size];    int right=0;    int wrong=0;    int i;    cout<<"Selecting and opening file: "<<endl;    if (!mFile.good())    {        cout<<"Can not open file."<<endl;        exit(EXIT_FAILURE);    }    for (i=0;i<Size;++i)    {        if (mFile>>temp[i])        {            ++right;            cout<<"No. "<<i+1<<"\t";            cout<<temp[i]<<endl;        }        //以下部分可以正常运行                  else        {            ++wrong;            mFile.clear();            while (mFile.get()!=' ')            {                continue;            }            cout<<"No. "<<i+1<<"\t";            cout<<"Data error"<<endl;        }    }    cout<<"Total got "<<right<<" data and "<<wrong<<" fails."<<endl;    if (mFile.eof())    {        cout<<"End of file."<<endl;    }    else if (mFile.fail())    {        cout<<"Can not read EOF of file."<<endl;    }    else    {        cout<<"Unkown error."<<endl;    }    mFile.close();    return 0;}


请教一下各位达人,为什么前面的程序这样使用就会出错?
如果前面的程序我要达到第二点要求,该如何处理?
谢谢……

[解决办法]
while (mFile.get()!="\n")改为while (mFile.get()!='\n')

读书人网 >C++

热点推荐