Skip to content

Parse Without Exceptions

The Course
•
40 min study

A line of input is text. The characters 25 are not the number 25 until something converts them, and input from people contains things that only look like numbers: 25x, two, an empty line, or 99999999999999999999 that would not fit in an int. A parser has two jobs, and the second is the harder one: produce the number when the text is valid, and refuse clearly when it is not, without leaving half-changed data behind.

A string stream lets you read typed values from text. Include <sstream> and construct std::istringstream input(line). Extraction with >> skips leading whitespace, then reads as many characters as form a valid value of the requested type. If no valid value starts there, or the value is too large for the type, extraction fails and puts the stream into a failed state. You check that failure through the stream's truth value, exactly as with std::getline.

Predict and run

Predict before running C++
#include <iostream>
#include <string>
#include <sstream>

bool parse_minutes(const std::string& text, int& out) {
    std::istringstream input(text);
    int candidate = 0;
    char extra = '\0';
    if (!(input >> candidate) || (input >> extra) || candidate < 1 || candidate > 180) {
        return false;
    }
    out = candidate;
    return true;
}

int main() {
    int minutes = 7;
    bool ok = parse_minutes("25", minutes);
    std::cout << ok << " " << minutes << "\n";
    ok = parse_minutes("25x", minutes);
    std::cout << ok << " " << minutes << "\n";
    return 0;
}
Check your prediction
Text
1 25
0 25

The second call failed, and minutes kept its previous value of 25. It did not become 0, and it did not become 7. The function only assigns to out after every check has passed, so a rejected input leaves the caller's variable exactly as it was.

A valid prefix is not a valid number

Extraction reads as far as it can. For 25x, it happily reads 25 and stops at the x, reporting success. If you only checked the first extraction, 25x would be accepted as 25. The parser therefore tries to read one more non-whitespace character. If that succeeds, there was junk after the number and the text is rejected. If it fails, only whitespace remained.

What extraction accepts on its own C++
#include <iostream>
#include <sstream>
#include <string>

void show(const std::string& text) {
    std::istringstream input(text);
    int value = 0;
    bool read = static_cast<bool>(input >> value);
    char extra = '\0';
    bool junk = static_cast<bool>(input >> extra);
    std::cout << "[" << text << "] read=" << read << " junk=" << junk << "\n";
}

int main() {
    show("25");
    show(" 25 ");
    show("25x");
    show("x25");
    show("");
    show("99999999999999999999");
    return 0;
}
Text
[25] read=1 junk=0
[ 25 ] read=1 junk=0
[25x] read=1 junk=1
[x25] read=0 junk=0
[] read=0 junk=0
[99999999999999999999] read=0 junk=0

Read the results line by line. Surrounding spaces are fine. 25x reads a number and has junk. x25 and the empty string fail at once, and so does the huge number, because it does not fit in an int. Notice the last three lines report junk=0 for a different reason: once a stream has failed, every later extraction from it also fails until the stream is reset. That sticky failure is why the planner creates a fresh string stream for every line instead of reusing one.

Validate, then commit

Getting a number out of the text is only the first check. The value must also satisfy the rules, here 1 through 180. The parser does all its work in a local candidate and assigns to the caller's out only at the very end. This "validate, then commit" pattern means a caller never sees a half-finished result. It matters even more for a record with several fields: if the minutes are written and then the title turns out to be invalid, a caller that trusted out would hold a mixture of old and new data.

The function reports success with a bool return value. C++ also has exceptions, and the standard function std::stoi uses them to report bad text, but this course's browser compiler does not support exceptions. Explicit bool results work everywhere and make the failure path visible at every call site.

Practice

Exercise

Your turn

Write bool parse_duration(const std::string& text, int& out) for text holding two integers, hours and minutes, such as "1 30". Rules: hours 0 through 3, minutes 0 through 59, a total of 1 through 180 minutes, and nothing but whitespace after the second number. On success store the total minutes in out; on failure leave out unchanged. Assert:

  • "1 30" gives 90, "0 45" gives 45 and "3 0" gives 180
  • "3 1", "0 0", "1 60", "1", "1 30 x" and "-1 30" all fail
  • after a failure, out still holds the last successful value

When all pass, print Duration checks passed.

Your workspace C++
#include <iostream>
#include <sstream>
#include <string>
#include <cassert>

int main() {
    // Write parse_duration above main and your assertions here.
    return 0;
}
Hint 1: the idea

Read both numbers into locals, check that both reads succeeded and that no junk follows, then check each range and the total. Assign out only after every check passes.

Hint 2: a first step

Write if (!(input >> hours >> minutes) || (input >> extra)) { return false; }. A chained extraction fails if either number is missing or invalid.

Show one solution
Run the solution C++
#include <iostream>
#include <sstream>
#include <string>
#include <cassert>

bool parse_duration(const std::string& text, int& out) {
    std::istringstream input(text);
    int hours = 0;
    int minutes = 0;
    char extra = '\0';
    if (!(input >> hours >> minutes) || (input >> extra)) {
        return false;
    }
    if (hours < 0 || hours > 3 || minutes < 0 || minutes > 59) {
        return false;
    }
    int total = hours * 60 + minutes;
    if (total < 1 || total > 180) {
        return false;
    }
    out = total;
    return true;
}

int main() {
    int out = 0;
    assert(parse_duration("1 30", out) && out == 90);
    assert(parse_duration("0 45", out) && out == 45);
    assert(parse_duration("3 0", out) && out == 180);
    assert(!parse_duration("3 1", out));
    assert(!parse_duration("0 0", out));
    assert(!parse_duration("1 60", out));
    assert(!parse_duration("1", out));
    assert(!parse_duration("1 30 x", out));
    assert(!parse_duration("-1 30", out));
    assert(out == 180);
    std::cout << "Duration checks passed\n";
    return 0;
}
Text
Duration checks passed

The checks run from "is this text at all?" to "is it in range?", and out is touched only on the last line. The range checks on hours and minutes come before the multiplication, so the arithmetic only ever sees small values and cannot overflow. The final assertion proves six rejections in a row left the last good value, 180, in place. Next you will parse a full task line: a number, a flag and a title with spaces in it.

Was this article helpful?

Your response is saved on this device.