Bestimmte Zeile aus einer Datei lesen



  • Ne kurze Frage:

    Wie kann ich aus einer Zeile eine bestimmte Zeile(z.B. Nur Zeile 4) auslesen?



  • Hallo Travis,

    indem Du drei Zeilen überliest und dann die folgende also 4.Zeile einliest. Das ist ein schönes Beispiel für einen Manipulator - etwa

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <limits>
    
    struct skiplines
    {
        explicit skiplines( int n ) : m_n( n ) {}
        friend std::istream& operator>>( std::istream& in, const skiplines& sl )
        {
            for( int n = sl.m_n; n > 0 && in; --n )
                in.ignore( std::numeric_limits< std::streamsize >::max(), 
                    std::istream::traits_type::to_int_type( '\n' ) );
            return in;
        }
    private:
        int m_n;
    };
    
    int main()
    {
        using namespace std;
        ifstream in( "input.txt" );
        std::string zeile4;
        if( getline( in >> skiplines( 3 ), zeile4 ) )
            cout << "[" << zeile4 << "]" << endl;
        return 0;
    }
    

    Gruß

    Werner



  • ne kurze frage noch

    du schreibst oben:

    using namespace std;
    

    ist unten dann noch
    {cpp]std::string[/cpp]
    nötig?



  • Hallo Travis,

    Nein; nach 'using namespace std' ist das std:: vor string natürlich unnötig. Das war mehr ein Versehen.

    Gruß
    Werner


Log in to reply