fork download
  1. #include <cstdlib>
  2. #include <iostream>
  3. #include <sstream>
  4. #include <stdexcept>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. int main() {
  10. const char* foo[] = { "12", "1X", "X2" };
  11.  
  12. for (auto& i : foo) {
  13. int temp = atoi(i);
  14.  
  15. (temp == 0) ? cout << "atoi: check string(0)\n" : cout << "atoi: " << temp << endl;
  16.  
  17. (istringstream(i) >> temp) ? cout << "istringstream::operator>>: " << temp << endl : cout << "istringstream::operator>>: error flag(0)\n";
  18.  
  19. try {
  20. cout << "stoi: " << stoi(i) << endl;
  21. } catch(const invalid_argument& e) {
  22. cout << "stoi: threw " << e.what() << endl;
  23. }
  24. }
  25. return 0;
  26. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
atoi: 12
istringstream::operator>>: 12
stoi: 12
atoi: 1
istringstream::operator>>: 1
stoi: 1
atoi: check string(0)
istringstream::operator>>: error flag(0)
stoi: threw stoi