Skip to content

Instantly share code, notes, and snippets.

@mshafae
Last active April 16, 2024 21:13
Show Gist options
  • Save mshafae/4d282935ea5deaf8c2e6aca83a9fcac8 to your computer and use it in GitHub Desktop.
Save mshafae/4d282935ea5deaf8c2e6aca83a9fcac8 to your computer and use it in GitHub Desktop.
CPSC 120 Example of reading a file line by line and storing each line into a std::vector
// Gist https://gist.github.com/mshafae/4d282935ea5deaf8c2e6aca83a9fcac8
// Filename cpsc120_filelines_to_vector.cc
// CompileCommand clang++ -std=c++17 cpsc120_filelines_to_vector.cc
// Read a file line by line and place contents into a std::vector
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char const *argv[]) {
std::vector<std::string> arguments{argv, argv + argc};
if (arguments.size() < 2) {
std::cout << "Please provide a path to a file.\n";
return 1;
}
std::string input_file_name{arguments.at(1)};
// https://en.cppreference.com/w/cpp/io/basic_ifstream
std::ifstream input_file_stream{input_file_name};
if (!input_file_stream.is_open()) {
std::cout << "Could not open the file " << input_file_name << "\n";
return 1;
}
std::vector<std::string> lines;
std::string line_buffer;
while (std::getline(input_file_stream, line_buffer)) {
lines.push_back(line_buffer);
}
if (input_file_stream.eof()) {
std::cout << "End of file reached successfully!\n";
} else if (input_file_stream.bad()) {
std::cout << "I/O error while reading.\n";
return 1;
} else if (input_file_stream.fail()) {
std::cout << "Failure: Long line.\n";
return 1;
}
// When you open something, close it!
input_file_stream.close();
for (const std::string a_line : lines) {
std::cout << a_line << "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment