#include <cstdlib>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>
using namespace std;
int main() {
const string foo[] = { "12", "1X", "X2" };
for (const auto& i : foo) {
{
char* size;
const int num = strtol(i.c_str(), &size, 10);
if(distance(i.c_str(), const_cast<const char*>(size)) == i.size()) {
cout << "strtol: " << num << endl;
} else {
cout << "strtol: error\n";
}
}
{
size_t size;
int num;
if(sscanf(i.c_str(), "%d%zn", &num, &size) == 1 && size == i.size()) {
cout << "sscanf: " << num << endl;
} else {
cout << "sscanf: error\n";
}
}
{
try {
size_t size;
const auto num = stoi(i, &size);
if(size == i.size()) {
cout << "stoi: " << num << endl;
} else {
throw invalid_argument("invalid stoi argument");
}
} catch(const invalid_argument& /*e*/) {
cout << "stoi: error\n";
}
}
}
return 0;
}
I2luY2x1ZGUgPGNzdGRsaWI+CiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPGl0ZXJhdG9yPgojaW5jbHVkZSA8c3RkZXhjZXB0PgojaW5jbHVkZSA8c3RyaW5nPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBtYWluKCkgewoJY29uc3Qgc3RyaW5nIGZvb1tdID0geyAiMTIiLCAiMVgiLCAiWDIiIH07CgoJZm9yIChjb25zdCBhdXRvJiBpIDogZm9vKSB7CgkJewoJCSAgICBjaGFyKiBzaXplOwoJCSAgICBjb25zdCBpbnQgbnVtID0gc3RydG9sKGkuY19zdHIoKSwgJnNpemUsIDEwKTsKCQkKCQkgICAgaWYoZGlzdGFuY2UoaS5jX3N0cigpLCBjb25zdF9jYXN0PGNvbnN0IGNoYXIqPihzaXplKSkgPT0gaS5zaXplKCkpIHsKCQkgICAgICAgIGNvdXQgPDwgInN0cnRvbDogIiA8PCBudW0gPDwgZW5kbDsKCQkgICAgfSBlbHNlIHsKCQkgICAgICAgIGNvdXQgPDwgInN0cnRvbDogZXJyb3JcbiI7CgkJICAgIH0KCQl9CgkJewoJCSAgICBzaXplX3Qgc2l6ZTsKCQ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