1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
// ReadFile est une fonction qui lit un fichier (variable fileName) et met son contenu dans un tableau de string (variable text)
bool ReadFile( vector<string> & text, const string & fileName )
{
ifstream file( fileName.c_str() );
if ( !file )
{
return false; // fichier non trouvé ou impossible à ouvrir en lecture.
}
string newLine;
vector<string>().swap( text ); // on vide le tableau, au cas où...
while ( getline( file, newLine ) ) // on lit une nouvelle ligne
{
text.push_back( newLine ); // on ajoute la ligne dans le tableau
}
return true;
}
int main( int argc, char** argv )
{
vector<string> text; // on déclare notre tableau de string
if ( !ReadFile( text, "test.txt" ) ) // on lit le fichier
{
cout << "fichier non trouvé" << endl;
return 1;
}
int count = 0;
for ( vector<string>::iterator it = text.begin(); it != text.end(); it++ )
{
// on affiche le fichier ligne par ligne dans la console
cout << "ligne " << count++ << ": " << *it << endl;
}
cin.get();
return 0;
} |
Partager