MyTetra Share
Делитесь знаниями!
Исключение (Exception)
Время создания: 16.08.2017 13:38
Раздел: Computer - Programming - C++

#include <iostream>

#include <sstream>

#include <iomanip>

#include <exception>


using namespace std;


struct Date

{

int year;

int month;

int day;

};


void EnsureNextSymbolAndSkip(stringstream& stream)

{

if(stream.peek() != '/')

{

throw exception();

}

stream.ignore(1);

}


Date ParseDate(const string& s)

{

stringstream stream(s);

Date result;

stream >> result.year;

EnsureNextSymbolAndSkip(stream);

stream >> result.month;

EnsureNextSymbolAndSkip(stream);

stream >> result.day;

return result;

}


int main()

{

string date_str = "2017/08/16";

//string date_str = "2017-08-16"; /*code with exception error*/

try

{

Date date = ParseDate(date_str);

cout << setw(2) << setfill('0') << date.day << '.'

<< setw(2) << setfill('0') << date.month << '.'

<< date.year << endl;

}

catch(exception& ex)

{

cout << "Exception has happened";

}


getchar();

return 0;

}


Обновленный вариант:


#include <iostream>

#include <sstream>

#include <iomanip>

#include <exception>


using namespace std;


struct Date

{

int year;

int month;

int day;

};


void EnsureNextSymbolAndSkip(stringstream& stream)

{

if(stream.peek() != '/')

{

stringstream ss;

ss << "expected / , but has: " << char(stream.peek());

throw runtime_error(ss.str());

}

stream.ignore(1);

}


Date ParseDate(const string& s)

{

stringstream stream(s);

Date result;

stream >> result.year;

EnsureNextSymbolAndSkip(stream);

stream >> result.month;

EnsureNextSymbolAndSkip(stream);

stream >> result.day;

return result;

}


int main()

{

//string date_str = "2017/08/16";

string date_str = "2017-08-16"; /*code with exception error*/

try

{

Date date = ParseDate(date_str);

cout << setw(2) << setfill('0') << date.day << '.'

<< setw(2) << setfill('0') << date.month << '.'

<< date.year << endl;

}

catch(exception& ex)

{

cout << "Exception has happened: " << ex.what();

}


getchar();

return 0;

}



...






 
MyTetra Share v.0.53
Яндекс индекс цитирования