Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Example to printf() doubles for #68.
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// Copyright (c) 2019 Dr. Colin Hirsch and Daniel Frey | ||
// Please see LICENSE for license or visit https://github.com/taocpp/json/ | ||
|
||
#include <cstdio> | ||
#include <iostream> | ||
|
||
#include <tao/json.hpp> | ||
|
||
namespace tao::json::events | ||
{ | ||
struct printf_doubles | ||
: public to_stream | ||
{ | ||
using to_stream::to_stream; | ||
|
||
void number( const double v ) | ||
{ | ||
next(); | ||
if( !std::isfinite( v ) ) { | ||
// if this throws, consider using non_finite_to_* transformers | ||
throw std::runtime_error( "non-finite double value invalid for JSON string representation" ); | ||
} | ||
char buffer[ 32 ]; | ||
const std::size_t n = std::snprintf( buffer, sizeof( buffer ), "%0.2f", v ); | ||
os.write( buffer, n ); | ||
} | ||
}; | ||
|
||
} // namespace tao::json::events | ||
|
||
int main( int argc, char** argv ) | ||
{ | ||
if( argc != 2 ) { | ||
std::cerr << "usage: " << argv[ 0 ] << " file.json" << std::endl; | ||
std::cerr << " parses the json file and writes it to stdout with '%0.2f' for doubles" << std::endl; | ||
return 1; | ||
} | ||
tao::json::events::printf_doubles consumer( std::cout ); | ||
tao::json::events::from_file( consumer, argv[ 1 ] ); | ||
return 0; | ||
} |