Консультация № 169752
22.06.2009, 20:30
0.00 руб.
0 1 1
Помогите решить задачку!!!
Написать функцию вычисления значения по заданной строке символов, являющихся записью этого числа в десятичной системе счисления. Предусмотреть случай выхода за границы диапазона определяемого типом int. Используйте механизм исключений.

Обсуждение

Неизвестный
23.06.2009, 01:50
общий
это ответ
Здравствуйте, Каминский Руслан Анатольевич.

Код:
#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;
}
}
Форма ответа