Created
April 16, 2024 21:16
-
-
Save mshafae/d6704ddbb9f360d6ccd53dc979cc4776 to your computer and use it in GitHub Desktop.
Read a file word by word and place contents into a std::vector
This file contains hidden or 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
// Gist https://gist.github.com/mshafae/d6704ddbb9f360d6ccd53dc979cc4776 | |
// Filename cpsc120_words_to_vector.cc | |
// CompileCommand clang++ -std=c++17 cpsc120_words_to_vector.cc | |
// Read a file word by word 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> words; | |
std::string word_buffer; | |
// Use the selection operator to read from input_file_stream one word | |
// at a time and store the word into word_buffer. | |
while (input_file_stream >> word_buffer) { | |
words.push_back(word_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_word : words) { | |
std::cout << a_word << "\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment