Search⌘ K
AI Features

Solution: The Data Cleaner

Explore how to read and write files in C++ efficiently by opening file streams, validating file access, reading line by line, and parsing data with stringstreams. Understand how to detect and handle invalid data entries while logging issues to maintain clean output files.

We'll cover the following...
C++
// Solution: validating and cleaning data using stream states
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
void createRawData() {
std::ofstream file("raw_readings.txt");
file << "23.5\n";
file << "24.1\n";
file << "ERROR_READING\n";
file << "22.8\n";
file << "INVALID\n";
file << "25.0\n";
}
int main() {
createRawData();
std::ifstream inputFile("raw_readings.txt");
std::ofstream outputFile("clean_readings.txt");
if (!inputFile || !outputFile) {
std::cerr << "Error opening files.\n";
return 1;
}
std::string line;
while (std::getline(inputFile, line)) {
std::stringstream ss(line);
double value;
// Attempt to extract a double from the string stream
ss >> value;
// Check if the extraction succeeded
if (!ss.fail()) {
outputFile << value << "\n";
} else {
std::cout << "Skipping invalid line: " << line << "\n";
}
}
std::cout << "Data cleaning complete." << std::endl;
return 0;
}
...