Skip to content
This repository was archived by the owner on Jul 19, 2022. It is now read-only.
This repository was archived by the owner on Jul 19, 2022. It is now read-only.

Failed to parse boolean with std::ios::exceptions set #58

@oliverskawronek

Description

@oliverskawronek

jsonxx is not able to parse a boolean values if the stream is set to throw exceptions.

settings.json

{
  "flag" : true
}

main.cpp

#include "jsonxx.h"
#include <fstream>

using namespace std;

int main(int argc, char* argv[]) {
  ifstream file;

  // let file throw exceptions
  file.exceptions(
    ifstream::failbit // Logical error on i/o operation
    | ifstream::badbit); // Read/writing error on i/o operation
  try {
    file.open("settings.json");

    jsonxx::Object settings;
    const bool success = settings.parse(file);
    if (!success) {
      throw ifstream::failure("JSON syntax error");
    }

    file.close();
    cout << "success" << endl;
  }
  catch (ifstream::failure e) {
    cout << "Unable to load settings: " << e.what() << endl;
  }

  cin.ignore();
  return 0;
}

error

iostream stream error

fault location
The failure occurs when jsonxx tries to parse the boolean value as number:

bool parse_number(std::istream& input, Number& value) {
    input >> std::ws;
    std::streampos rollback = input.tellg();
    input >> value; // <--- iostream stream error
    if (input.fail()) {
        input.clear();
        input.seekg(rollback);
        return false;
    }
    return true;
}

possible fix

bool parse_number(std::istream& input, Number& value) {
    input >> std::ws;
    std::streampos rollback = input.tellg();
    bool failed = true;
    try {
        input >> value;
        if (!input.fail()) {
            failed = false;
        }
    } catch (std::ios::failure& e) {
        if (!input.fail()) {
            throw;
        }
    }
    if (failed) {
        input.clear();
        input.seekg(rollback);
        return false;
    }
    return true;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions