wk01_basic_concepts


Basic C++ Concepts

C++ program that demonstrates both file I/O for processing a large dataset and a command-line tool for initializing a simulation. This example will focus on a simple 2D grid-based simulation, where we'll read initial data, process it, and then use command-line arguments to set up a simulation grid.

Resources (C++ Tutorial)

algorithm, auto, command_line_arguments, exception, iostream, namespace, range-based, sstream, std::cin, std::cout, std::cerr, std::exception, std::ifstream, std::ofstream, stdexcept, throw, vector

Structure

Implementation

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <stdexcept>
#include <cmath>

// Function to read data from file, normalize it, and write to output file
void processDataset(const std::string& inputFile, const std::string& outputFile) {
    std::ifstream inFile(inputFile);
    if (!inFile) {
        throw std::runtime_error("Unable to open input file: " + inputFile);
    }

    std::vector<double> data;
    double value;
    while (inFile >> value) {
        data.push_back(value);
    }
    inFile.close();

    if (data.empty()) {
        throw std::runtime_error("No data read from file");
    }

    // Normalize data
    double min = *std::min_element(data.begin(), data.end());
    double max = *std::max_element(data.begin(), data.end());
    double range = max - min;

    std::ofstream outFile(outputFile);
    if (!outFile) {
        throw std::runtime_error("Unable to open output file: " + outputFile);
    }

    for (double& val : data) {
        val = (val - min) / range;
        outFile << val << "\n";
    }
    outFile.close();

    std::cout << "Data processed and written to " << outputFile << std::endl;
}

// Function to initialize and print a 2D grid
void initializeGrid(int width, int height, double initialValue) {
    std::vector<std::vector<double>> grid(height, std::vector<double>(width, initialValue));

    std::cout << "Initial grid configuration (" << width << "x" << height << "):\n";
    for (const auto& row : grid) {
        for (double val : row) {
            std::cout << val << " ";
        }
        std::cout << "\n";
    }
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <mode> [args...]\n";
        std::cerr << "Modes:\n";
        std::cerr << "  process <input_file> <output_file>\n";
        std::cerr << "  simulate <grid_width> <grid_height> <initial_value>\n";
        return 1;
    }

    std::string mode = argv[1];

    try {
        if (mode == "process") {
            if (argc != 4) {
                throw std::runtime_error("Process mode requires input and output file names");
            }
            processDataset(argv[2], argv[3]);
        }
        else if (mode == "simulate") {
            if (argc != 5) {
                throw std::runtime_error("Simulate mode requires grid width, height, and initial value");
            }
            int width = std::stoi(argv[2]);
            int height = std::stoi(argv[3]);
            double initialValue = std::stod(argv[4]);
            initializeGrid(width, height, initialValue);
        }
        else {
            throw std::runtime_error("Unknown mode: " + mode);
        }
    }
    catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

This program demonstrates the following concepts:

  1. File I/O (input-output):
  2. The processDataset function reads data from an input file, processes it (normalizes the values), and writes the processed data to an output file.
  3. It uses std::ifstream for reading and std::ofstream for writing.

  4. Command-line Interface:

  5. The program uses command-line arguments to determine its mode of operation and parameters.
  6. It supports two modes: "process" for data processing and "simulate" for grid initialization.

  7. Includes:

  8. The program uses <iostream> for standard I/O operations.
  9. It uses <string> for string manipulation.
  10. Additional headers like <fstream>, <vector>, <algorithm>, etc., are included for various functionalities.

  11. Data Processing:

  12. The program demonstrates data normalization as an example of processing.

  13. Grid Initialization:

  14. The initializeGrid function creates a 2D grid based on user-specified dimensions and initial value.

  15. Error Handling:

  16. The program uses exception handling to manage errors and provide informative messages.

To use this program, you can compile it and then run it in two modes:

  1. Process data: ./program process input.txt output.txt

  2. Initialize simulation grid: ./program simulate 5 5 1.0

This example provides a foundation for more complex scientific computing applications, demonstrating how to handle data input/output and set up initial conditions for simulations based on user input.

Previous Page | Course Schedule | Course Content