0

我需要从文件中读取,然后将行分成 3 个字符串。格式是:A first_Secod_Third(三个下划线)这是作业,他们建议我们使用getline和忽略。所以我有:

    main()
    ifstream inf("file.txt")
    while(inf)
    {inf >> class1;
    cout << class1;
    }
    class THECLASS
    {string a, b, c;
    public:
    friend void operator>>(ifstream &inf, THECLASS &class1)
    {getline(inf, class1.a, '_');
    inf.ignore();
    inf.ignore();
    [if I put getline class1.b, the whole line will go into it, overwriting .a]
    }

and in operator<<, I have

    os << class1.a << class1.b;
    return os;

但是当我 cout << class1 得到的只是输入文件的所有三个字段,没有_,每个字段都在一个新行上。当我尝试使用 get() 函数时,即使我声明了 fstream,编译器也无法识别它。这样做的一般算法是什么?

4

1 回答 1

0

希望这可以帮助你。

// assume the content of infile : 
//First1_xxSecond1_xxThird1
//Firts2_xxSecond2_xxThird2
//First3_xxSecond3_xxThird3
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class MyClass
{   
public:
    string a, b, c;
};
ifstream& operator>>(ifstream &inf, MyClass& class1)
{
    getline(inf, class1.a, '_');    //"First" into class1.a
    inf.ignore(2,EOF);              //skip "xx"
    getline(inf, class1.b, '_');
    inf.ignore(2, EOF);
    getline(inf, class1.c);
    return inf;
}
ostream&  operator<<(ostream& out, const MyClass& class1)
{
    out<< class1.a << "_"<< class1.b<< "_" << class1.c;
    return out;  
}
int main () { 
    MyClass class1;
    ifstream  stream("test.txt");
    while(stream.rdstate()  != ifstream::eofbit)
    {
        stream >> class1;
        cout << class1 <<"\n";  //First1_Second1_Third1 for the first loop.ect
    }
    return 0;
}
于 2012-05-27T04:16:31.300 回答