01-basic.cpp 953 B

123456789101112131415161718192021222324252627282930313233
  1. // Convert text to number and yield expected with number or error text.
  2. #include "nonstd/expected.hpp"
  3. #include <cstdlib>
  4. #include <iostream>
  5. #include <string>
  6. using namespace nonstd;
  7. using namespace std::literals;
  8. auto to_int( char const * const text ) -> expected<int, std::string>
  9. {
  10. char * pos = nullptr;
  11. auto value = strtol( text, &pos, 0 );
  12. if ( pos != text ) return value;
  13. else return make_unexpected( "'"s + text + "' isn't a number" );
  14. }
  15. int main( int argc, char * argv[] )
  16. {
  17. auto text = argc > 1 ? argv[1] : "42";
  18. auto ei = to_int( text );
  19. if ( ei ) std::cout << "'" << text << "' is " << *ei << ", ";
  20. else std::cout << "Error: " << ei.error();
  21. }
  22. // cl -EHsc -wd4814 -I../include 01-basic.cpp && 01-basic.exe 123 && 01-basic.exe abc
  23. // g++ -std=c++14 -Wall -I../include -o 01-basic.exe 01-basic.cpp && 01-basic.exe 123 && 01-basic.exe abc
  24. // '123' is 123, Error: 'abc' isn't a number