Created
August 23, 2022 12:14
-
-
Save andr1972/cf9b3a583b3e6b7890acf9c971fa36cc to your computer and use it in GitHub Desktop.
Read lines from text stream to vector in C++
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
//https://stackoverflow.com/questions/73446872/read-last-empty-line-of-a-text-file-in-c/73458476#73458476 | |
/* | |
* it distinguishes between lastline with and wihout \n | |
* getline().good() returns true if after line is newline char. | |
* Push to vector last not good(), thus I must check if file is not empty (peek()) | |
* */ | |
#include <iostream> | |
#include <fstream> | |
#include <vector> | |
using namespace std; | |
vector<string> readLines(string filename) | |
{ | |
ifstream infile(filename); | |
vector<string> v; | |
string line; | |
bool readedNewline; | |
if (infile.peek() != EOF) | |
while(true) { | |
readedNewline = getline(infile, line).good(); | |
v.push_back(line); | |
if (!readedNewline) break; | |
} | |
return v; | |
} | |
int main() { | |
auto v = readLines("test.txt"); | |
for (auto &line:v) | |
cout << ">" << line << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment