Skip to content

Instantly share code, notes, and snippets.

@sergnechaev
Last active October 6, 2018 09:29
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
C++ read text file to a vector of lines or a string
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
std::vector<std::string> utils::files::readLines(const std::string& filename) {
std::ifstream ifs(filename);
std::vector<std::string> lines;
if (!ifs) {
std::cerr << "Cannot open file: " << filename << std::endl;
} else {
for (std::string line; std::getline(ifs, line); /**/) {
lines.push_back(line);
}
std::cout << std::to_string(lines.size()) << " lines read from [" << filename << "]" << std::endl;
}
return lines;
}
std::string utils::files::readFileToString(const std::string& file) {
std::cout << "Read string from file [" << file << "]" << std::endl;
std::ifstream t(file);
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment