【问题标题】:Reading from a file (ifstream) and sorting从文件中读取(ifstream)并排序
【发布时间】:2012-05-27 03:06:06
【问题描述】:

我需要从文件中读取,然后将行分成 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 _,每个字段都在一个新行上。 当我尝试使用 get() 函数时,即使我声明了 fstream,编译器也无法识别它。 这样做的一般算法是什么?

【问题讨论】:

    标签: fstream getline


    【解决方案1】:

    希望对你有帮助。

    // 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;
    }
    

    【讨论】:

    • 实际上有,三个下标。在那种情况下,我应该需要两个 inf.ignore() 语句,对吧?尽管如此,对于我的最后一个条目,它正确读取了 a b c,然后创建了另一个 b 和 c。不过我觉得我的课有问题....
    • 抱歉误解了你的观点,你想要 First_Second_Third 作为输出格式吗?我只是以为是inf格式,你能给我源数据格式吗?如果你想要输出格式,在 operator
    • 感谢您的工作,Ticks!您的第一个代码帮助我解决了它。我在 inf 中多写了一行,因为我没有在正确的位置放置 break 语句,但对于其余部分,它工作得很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多