C++ · Intermediate level

Intermediate level · Module 4: Files, Streams and Exceptions in C++ · Lesson 2 of 3

Parsing CSV with String Streams

Split CSV lines into fields, convert them to numbers safely and collect malformed lines for reporting.

In this lesson you will

  • Split lines on commas with getline and a delimiter
  • Convert text to numbers and detect conversion errors

Key concepts

getline with delimiterstd::istringstreamstd::stoi / std::stodmalformed input

The lesson

Wrap a line in std::istringstream and call std::getline(fields, cell, ',') repeatedly to split it on commas into a std::vector<std::string>. Check the number of fields before using them.

Convert text with std::stoi and std::stod. They throw std::invalid_argument for text that is not a number and std::out_of_range for values that do not fit, so wrap conversions in try/catch and record the problem with the line number.

Collect problems rather than stopping at the first one: a report listing every bad line lets someone fix the source file in one pass.

Step by step

  1. Split one CSV line into fields.
  2. Convert the quantity and price fields to numbers.
  3. Catch conversion errors and record the line number.
  4. Print a summary of valid rows and a list of bad lines.

Practice activity

Complete the pharmacy CSV practical: load valid stock, list malformed lines and write the reorder file.

Expected result: The reorder file is correct and every malformed line is reported with its number and reason.

Check your understanding

  1. Which function splits a stream on a delimiter?

    Show answer

    std::getline with a delimiter argument.

  2. What does std::stoi throw for the text 'ten'?

    Show answer

    std::invalid_argument.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.