注册 登录
编程论坛 C++教室

文件流读取,多读出一个0

最近不在 发布于 2010-07-13 18:21, 791 次点击
程序代码:
// Note:Your choice is C++ IDE
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;

struct cmd
{
    string a;
    string b;
    int c;
    friend ostream& operator << (ostream &os, const cmd& t);
    friend istream& operator >> (istream &is, cmd& t);
};

ostream& operator << (ostream &os, const cmd& t)
{
    os<<t.a<<'\t'<<t.b<<'\t'<<t.c;

    return os;
}

istream& operator >> (istream &is, cmd& t)
{
    is.sync();
    getline(is, t.a, '\\');
    getline(is, t.b, '\\');
   
    char ch[10];
    is>>ch;
    t.c = atoi(ch);
   
    return is;
}

int main()
{
    cmd a[2];
    cmd b;
    vector<cmd> obj;
   
    ofstream outfile("g:\\ct.txt");
    for(int i = 0 ; i != 2; ++i)
    {
        cin>>a[i];
        outfile<<a[i]<<endl;
    }
   
    outfile.close();
   
    ifstream infile("g:\\ct.txt");

    while( !infile.eof() )
    {
        infile>>b;
        obj.push_back(b);
        cout<<b<<endl;
    }
   
    /*while( 1 )
    {
        if( infile.fail() )
        {
            break;
        }
        infile>>b;
        obj.push_back(b);
        cout<<b<<endl;
    }
*/
   
    outfile.clear();
   
    for(vector<cmd>::iterator iter = obj.begin(); iter != obj.end(); ++iter)
    {
        cout<<*iter<<endl;
    }
      
    return 0;
}ab c\t t\1
fg\t t\45
ab c    t t     1
fg      t t     45
                0
ab c    t t     1
fg      t t     45
                0



             Press any key to continue


[ 本帖最后由 最近不在 于 2010-7-13 18:43 编辑 ]
3 回复
#2
最近不在2010-07-15 14:44
就是多读取了一行,最后一个数据成员多出了值。求解!
#3
东海一鱼2010-07-15 16:14
不是多读取一行的问题,是你没有重载文件流到对象成员的方法。

所以你实际读取的是:
obj.a = 'ab c    t t     1
        fg      t t     45'

obj.b = ''
obj.c = 0
所以才有此现象,你DUMP一下成员值就看到了。
#4
jmchang2010-07-17 16:39
多出一个O就会出现错误了。
1