///////////////////////////////////////////////////////////////////// // Convert.cpp - Implement serialization to and from strings // // ver 1.1 // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2017 // ///////////////////////////////////////////////////////////////////// #include "Convert.h" #include "..\Utilities\Utilities.h" #include #include ///////////////////////////////////////////////////////////////////// // Widget class - shows user defined types can be converted // - must have operator<< and operator>> class Widget { public: Widget(const std::string& str = "") : state(str) {} std::string& value() { return state; } private: std::string state; }; std::ostream& operator<<(std::ostream& out, Widget& widget) { out << widget.value(); return out; } std::istream& operator >> (std::istream& in, Widget& widget) { std::string temp; while (in.good()) // extract all the words from widget's string state { in >> temp; widget.value() += temp + " "; } return in; } #ifdef TEST_CONVERT ///////////////////////////////////////////////////////////////////// // Demo code int main() { Title("Demonstrating Converting"); putLine(); subTitle("Demonstrating Conversion of numerical types"); std::string intString = Convert::toString(42); std::cout << "\n conversion of integer: " << intString; std::cout << "\n retrieving integer: " << Convert::fromString(intString); putLine(); std::string dblString = Convert::toString(3.1415927); std::cout << "\n conversion of double: " << dblString; std::cout << "\n retrieving double: " << Convert::fromString(dblString); putLine(); subTitle("Demonstrating Conversion of instances of Widget classe"); Widget widget("Joe Widget"); std::string wdgString = Convert::toString(widget); std::cout << "\n conversion of Widget: " << wdgString; Widget newWdg = Convert::fromString(wdgString); std::cout << "\n retrieved instance of: " << Convert::id(newWdg); std::cout << "\n Widget's value is: " << newWdg.value(); putLines(2); } #endif