Saltar al contenido
Back to home
Session 01 C++ 2025-2026 1º

Introduction to CSV in C++

Reading data from CSV files and implementing basic processing algorithms.

Key Concepts

  • File reading: std::ifstream
  • Data structures: struct and std::vector
  • String splitting
  • Converting text to numbers
  • Data validation and error handling
  • Basic calculations (sum, average)

Files


Mandatory Steps

  1. Open the CSV file and read it line by line.
std::ifstream file("datos.csv");

if (!file) {
    std::println("Could not open the file");
    return 1;
}

std::string line;
while (std::getline(file, line)) {
    // process each line
}
  1. Split each line into fields (student name, grades, etc.).
  2. Process only valid grades (ignore empty or non-numeric fields).
  3. Convert text values to numbers (std::stod or equivalent).
  4. Sum the valid grades for each student.
  5. Count how many valid grades there are.
  6. Calculate the average (sum / count).
  7. Display each student's average on the screen.

Extra Steps

  1. Detect lines with more or fewer columns than expected and display a warning.
  2. Continue execution even if some lines contain errors.
  3. Calculate the global average of all valid grades in the file.
  4. Calculate the maximum and minimum grades among all students.
  5. Ask the user whether the “Exam” column should be included and act accordingly.
  6. Display averages with a fixed number of decimal places chosen by the user.
  7. Organize the code into clear functions: read, process, and calculate.
  8. Avoid unnecessary code duplication.