Skip to content

Instantly share code, notes, and snippets.

@stungeye
Created January 13, 2022 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stungeye/550ebe0cb4fbc6d9264162d63d7986ca to your computer and use it in GitHub Desktop.
Save stungeye/550ebe0cb4fbc6d9264162d63d7986ca to your computer and use it in GitHub Desktop.
This is some data.
42
I am a goat. (This is 13 percent untrue.)
#include <iostream>
#include <filesystem>
#include <fstream>
#include <vector>
int main() {
std::cout << "CWD: " << std::filesystem::current_path() << "\n";
std::ifstream inputFile{"data.txt"};
if (!inputFile) {
std::cerr << "There was an issue opening this file.\n";
}
// While Loop to Consume File Data Until EOF (End Of File)
// Stream the data from the input stream into a string.
// Delimited by spaces and newlines.
// But why are we able to get into the loop once past EOF???
std::cout << "\nSTREAM READING DELIMITED BY SPACES AND NEWLINES: \n\n";
while (!inputFile.eof()) {
// Loop until we reach the end of file.
std::string data;
inputFile >> data;
std::cout << "##" << data << "##\n";
}
// inputFile.clear(); // Only needed if we have consumed an EOF... which we haven't.
inputFile.seekg(0); // Set position in input sequence to 0. (g for get)
std::cout << "\n\nLINE BY LINE READING OF THE SAME FILE: \n\n";
while (!inputFile.eof()) {
std::string line;
std::getline(inputFile, line); // NOTE: line is an "out parameter"
std::cout << "##" << line << "##\n";
}
std::cout << "\n\nREADING IN OUR NUMBERS:\n\n";
std::ifstream numberFile{"numbers.csv"};
if (!numberFile) {
std::cerr << "There was an issue opening this file.\n";
}
std::vector<int> numbers;
while (!numberFile.eof()) {
int number;
if (numberFile >> number) {
// Did our integer read succeed?
numbers.push_back(number); // Push the int into our vector.
} else {
// Looks like we read in either our delimiter or an unexpected char.
numberFile.clear(); // Clear the fail bit, otherwise we can't read any further.
char delimiter;
numberFile >> delimiter; // Read in the character that triggered the read error.
// Is it our delimiter?
if (delimiter != ',') {
// If not print it out to the standard error stream.
std::cerr << "Read in bad char: [" << delimiter << "]\n";
}
}
}
std::cout << "\n\nTHE CONTENTS OF OUR NUMBERS VECTOR:\n\n";
for (auto number : numbers) {
std::cout << number << "\n";
}
}
We can make this file beautiful and searchable if this error is corrected: It looks like row 4 should actually have 5 columns, instead of 10. in line 3.
93,23,2342,123,532
123,23423,8,87,123
1,2,3,4,5
10,9,8,7,6,5,4,3,2,1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment