A strong answer
Start with the data: a line like 42,Ada,30 is just text. You need three steps: split on commas, convert each slice to the right type, and validate the result.
For splitting, use std::string_view over the original line — no copy. Walk the view with a position index, find the next comma, substr the field, advance past the comma. This is O(n) on the line length with zero allocations.
For conversion, use std::from_chars (C++17). It takes a pointer range and an output reference, returns {ptr, ec}. Check ec == std::errc{} for success, and ptr == end to ensure the whole field was a valid number — from_chars stops at the first non-digit, so 123abc would parse as 123 with ptr pointing at a. The ptr == end check rejects that. from_chars is noexcept, has no locale dependence, and does no heap allocation. It is strictly safer and faster than std::stoi/std::stod, which throw on failure, skip whitespace silently, and can allocate.
Empty fields: substr returns an empty view. from_chars on empty fails with errc::invalid_argument, which is correct — an empty string is not a valid integer. If your format allows optional fields, check for empty before calling from_chars and treat it as a missing value (e.g., std::optional<int>).
Malformed lines (wrong field count, non-numeric age): the parser returns std::nullopt or a boolean false. The caller decides: skip, log, or abort. Never let a partially parsed struct escape into your data structures.
What the interviewer is listening for
string_view+ position index for zero-copy splitting.from_charsfor conversion, with theptr == endfull-consumption check.- Explicit handling of empty fields and malformed input.
- Why
from_charsbeatsstoi: noexcept, no locale, no allocation, exact consumption check. - Return type that forces the caller to handle failure (
optional,expected, or bool+out-param).
Common mistakes
- Using
stoi/stodand catching exceptions — slow, locale-sensitive, silent whitespace skipping. - Forgetting the
ptr == endcheck, so123abcbecomes 123 without warning. - Modifying the original string (e.g.,
strtok) instead of usingstring_view. - Not advancing the position past the delimiter, causing the next field to start with a comma.
- Letting a partially parsed object leak into a container — always validate before insert.