Чтобы прочитать весь файл на C++ с помощью getline()
, вы можете использовать различные методы. Вот несколько подходов:
Метод 1: использование цикла while и getline()
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("filename.txt");
std::string line;
if (file.is_open()) {
while (std::getline(file, line)) {
// Process the line as needed
std::cout << line << std::endl;
}
file.close();
} else {
std::cout << "Unable to open the file." << std::endl;
}
return 0;
}
Метод 2: использование цикла for и getline()
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("filename.txt");
std::string line;
if (file.is_open()) {
for (std::string line; std::getline(file, line);) {
// Process the line as needed
std::cout << line << std::endl;
}
file.close();
} else {
std::cout << "Unable to open the file." << std::endl;
}
return 0;
}
Метод 3: использование цикла do- while и getline()
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("filename.txt");
std::string line;
if (file.is_open()) {
do {
std::getline(file, line);
// Process the line as needed
std::cout << line << std::endl;
} while (!file.eof());
file.close();
} else {
std::cout << "Unable to open the file." << std::endl;
}
return 0;
}
Эти методы читают файл построчно, используя getline()
, пока не будет достигнут конец файла. Каждую строку можно обрабатывать или сохранять по мере необходимости.