Page 1 of 1

[C++] Cum citesc un fisier text linie cu linie?

Posted: 08 Apr 2009, 12:11
by Ovidiu Cucu
Intrebare: Cum citesc un fisier text linie cu linie?
Raspuns: Folosim functia std::getline definita in headerul <string>.

Exemplu
Functia read_text_file citeste liniile unui fisier text si le pune intr-un vector.

Code: Select all

#include <fstream>
#include <string>
#include <vector>

bool read_text_file(const std::string& name, std::vector<std::string>& v)
{
    v.clear();                          // clear the vector
    std::ifstream file(name.c_str());   // open file for reading
    bool isopen = file.is_open();       // check if successfuly open
    if(isopen)
    {
        std::string line;
        while(std::getline(file, line)) // get the line
        {
            v.push_back(line);          // put line in the vector
        }
    }
    return isopen; // return true if succeeded
}
Vezi si [MFC] Cum citesc un fisier text, line cu linie


Next FAQ >>