Reading Phone Numbers with an Overloaded Stream Extraction Operator. - C++ File Stream

C++ examples for File Stream:cin

Description

Reading Phone Numbers with an Overloaded Stream Extraction Operator.

Demo Code

#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>

class PhoneNumber {
 public:/*from  w w  w  .ja va  2  s .  com*/
    friend std::ostream& operator<<(std::ostream&, const PhoneNumber&);
    friend std::istream& operator>>(std::istream&, PhoneNumber&);

 private:
    char pNumber[15] = {};
    std::string areaCode;
    std::string exchange;
    std::string line;
};



std::ostream& operator<<(std::ostream& out, const PhoneNumber& number) {
    out << "(" << number.areaCode << ") " << number.exchange << "-" << number.line;

    return out;
}
std::istream& operator>>(std::istream& in, PhoneNumber& number) {
    in.read(&number.pNumber[0], 14);

    if (in.gcount() != 14 ||
        (number.pNumber[1] == '0' || number.pNumber[1] == '1') ||
        (number.pNumber[2] != '0' && number.pNumber[2] != '1') ||
        (number.pNumber[6] == '0' || number.pNumber[6] == '1')) {
        // set failbit
        in.setstate(std::ios::failbit);
    } else {
        char* ptrNumber = &number.pNumber[0];

        // area code
        while (*++ptrNumber != ')') {
            number.areaCode += *ptrNumber;
        }

        // increment to remove space
        ++ptrNumber;

        // exchange
        while (*++ptrNumber != '-') {
            number.exchange += *ptrNumber;
        }

        // line
        while (*ptrNumber++ != '\0') {
            number.line += *ptrNumber;
        }

        ptrNumber = nullptr;
    }

    return in;
}




int main(int argc, const char *argv[]) {
    PhoneNumber phone;

    std::cout << "Enter phone number in the form (800) 555-1212: ";
    std::cin >> phone;

    if (std::cin.fail()) {
        std::cout << "ERROR: Incorrect Input" << std::endl;
    } else {
        std::cout << "The phone number entered was: ";
        // std::cout << phone invokes operator<< by implicitly issuing
        // the non-member function call operator<<(std::cout, phone)
        std::cout << phone << std::endl;
    }

    return 0;
}

Result


Related Tutorials