To provide custom formatted data retrieval.
extractor prototype
Basic_istream &operator >>(basic_istream &s,const imanip<T>&)
{ // procedures
return s;
}
You may overload the extractor operator to tailor the specific needs of a particular class.
The this pointer is returned.
#include <iostream> #include <iomanip> #include <cstdlib> #include <cstring> class phonebook { friend std::ostream &operator<<(std::ostream &stream, phonebook o); friend std::istream &operator>>(std::istream &stream, phonebook &o); private: char name[80]; int areacode; int exchange; int num; public: void putname() {std::cout << num;} phonebook() {}; // default constructor phonebook(char *n, int a, int p, int nm) {std::strcpy(name, n); areacode = a; exchange = p; num = nm;} }; int main() { using namespace std; phonebook a; cin >> a; cout << a; return 0; } std::ostream &operator<<(std::ostream &stream, phonebook o) { using namespace std; stream << o.name << " "; stream << "(" << o.areacode << ") "; stream << o.exchange << "-"; cout << setfill('0') << setw(4) << o.num << "\n"; return stream; } std::istream &operator>>(std::istream &stream, phonebook &o) { using namespace std; char buf[5]; cout << "Enter the name: "; stream >> o.name; cout << "Enter the area code: "; stream >> o.areacode; cout << "Enter exchange: "; stream >> o.exchange; cout << "Enter number: "; stream >> buf; o.num = atoi(buf); cout << "\n"; return stream; }
Result:
Enter the name: CodeWarrior Enter the area code: 512 Enter exchange: 996 Enter number: 5300 CodeWarrior (512) 996-5300