fstream bestimmte Ausgabe vom Text



  • Hallo, ich komme gerade nicht weiter wie kann ich aus einer Textdatei in einer bestimmten Zeile was auslesen. Sagen wir mal als Beispiel Zeile 4 Zeichen 9.

    Ich lade die Datei in einem char array aber ich brauche nicht die ganze Datei.

    Ich benutzte #include <fstream>



  • Hallo drcubeman,

    eine ähnliche Frage hatten wir schon mal - z.B.: https://www.c-plusplus.net/forum/311915-full oder Du machst es so:

    #include <fstream>
    #include <iostream>
    #include <limits>
    
    int main()
    {
        using namespace std;
        ifstream file("Datei.txt");
        if( !file.is_open() )
        {
            cerr << "Fehler beim Oeffnen der Datei" << endl;
            return 0;
        }
        int zeile = 4;
        int spalte = 9;
        for( int z = 1; z < zeile; ++z )
            file.ignore( numeric_limits< streamsize >::max(), '\n' ); // eine Zeile überspringen
        file.ignore( spalte-1 );
    
        char c;
        if( file >> c )
        {
            cout << "Zeichen in Zeile " << zeile << " Spalte " << spalte << " = '" << c << "'" << endl;
        }
        return 0;
    }
    

    Was hat die Datei für ein Format? und was benötigst Du in Deiner Applikation in welcher Form?

    Gruß
    Werner



  • Plan B:

    #include <cstddef>
    #include <stdexcept>
    #include <string>
    #include <iostream>
    
    char get_char_at( std::istream & is, std::size_t row, std::size_t column )
    {
    	assert( is && row && column );
    
    	is.seekg( 0 );
    	std::string line;
    	std::size_t i{};
    
    	for( ; i < row && is.good(); ++i )
    		std::getline( is, line );
    
    	if( i != row || column > line.length() )
    		throw std::runtime_error( "row / column out of range!" );	
    
    	return line[ column - 1 ];
    }
    


  • Habt vielen Dank es funktioniert super ^^ 👍 👍 👍 👍 👍


Anmelden zum Antworten