fork(1) download
  1. #include <cstdlib>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <stdexcept>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. int main() {
  10. const string foo[] = { "12", "1X", "X2" };
  11.  
  12. for (const auto& i : foo) {
  13. {
  14. char* size;
  15. const int num = strtol(i.c_str(), &size, 10);
  16.  
  17. if(distance(i.c_str(), const_cast<const char*>(size)) == i.size()) {
  18. cout << "strtol: " << num << endl;
  19. } else {
  20. cout << "strtol: error\n";
  21. }
  22. }
  23. {
  24. size_t size;
  25. int num;
  26.  
  27. if(sscanf(i.c_str(), "%d%zn", &num, &size) == 1 && size == i.size()) {
  28. cout << "sscanf: " << num << endl;
  29. } else {
  30. cout << "sscanf: error\n";
  31. }
  32. }
  33.  
  34. {
  35. try {
  36. size_t size;
  37. const auto num = stoi(i, &size);
  38.  
  39. if(size == i.size()) {
  40. cout << "stoi: " << num << endl;
  41. } else {
  42. throw invalid_argument("invalid stoi argument");
  43. }
  44. } catch(const invalid_argument& /*e*/) {
  45. cout << "stoi: error\n";
  46. }
  47. }
  48. }
  49. return 0;
  50. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
strtol: 12
sscanf: 12
stoi: 12
strtol: error
sscanf: error
stoi: error
strtol: error
sscanf: error
stoi: error