#include <iostream>
#include <exception>
#include <limits>
using namespace std;
class OutOfRangeException : public exception
{
public:
OutOfRangeException()
:exception()
{}
public:
OutOfRangeException(const char* const & what)
:exception(what)
{}
public:
OutOfRangeException(const OutOfRangeException& rhs)
:exception(rhs)
{}
};
class FormatException : public exception
{
public:
FormatException()
:exception()
{}
public:
FormatException(const char* const & what)
:exception(what)
{}
public:
FormatException(const FormatException& rhs)
:exception(rhs)
{}
};
int ParseInt(const char* str)
{
static const int BASE = 10;
int value = 0;
int sign = 1;
if (!*str) {
throw FormatException("Passed string is not in a valid format.");
}
for (const char* p = str; *p; ++p) {
switch (*p) {
case '+': case '-':
// check that we are at the beginning of the string
if (p != str) {
throw FormatException("Passed string is not in a valid format.");
}
if (*p == '-') {
sign = -1;
}
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
// check range limits
if (value > numeric_limits<int>::max() / BASE) {
throw OutOfRangeException("Value range overflow.");
}
// add digit
value = value * BASE + (*p - '0');
break;
default:
throw FormatException("Passed string is not in a valid format.");
break;
}
}
return value * sign;
}
int main()
{
try {
cout << ParseInt("1") << endl;
}
catch (exception& ex) {
cout << ex.what() << endl;
}
}
Если Вы уже зарегистрированы на Портале - войдите в систему, если Вы еще не регистрировались - пройдите простую процедуру регистрации.