Last active
October 6, 2018 09:29
-
-
Save sergnechaev/d788ce3623935efa58e6ef1af668b8af to your computer and use it in GitHub Desktop.
C++ read text file to a vector of lines or a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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