Using cin

0 kazu lin · October 4, 2014
How to create personal information using cin???

the output is 
                            "PERSONAL INFORMATION"
             
                             NAME:
                             Age:
                             Gender:
                             Contact no:

Post a Reply

Replies

Oldest  Newest  Rating
0 Horacio Accipiter · October 4, 2014
This is how:


#include <iostream>
#include <string>
#include <cstdint>
#include <limits>

enum class Gender { Female, Male };

std::istream & operator>>(std::istream & is, Gender & gender) {
    std::string input;
    is >> input;
    if (input == "female") {
        gender = Gender::Female;
    } else if (input == "male") {
        gender = Gender::Male;
    } else {
        is.setstate(std::ios_base::failbit);
    }
    return is;
}

std::ostream & operator<<(std::ostream & os, Gender const & gender) {
    switch (gender) {
    case Gender::Male:
        os << "male";
        break;
    case Gender::Female:
        os << "female";
        break;
    }
    return os;
}

struct PersonalInformation {
    std::string name;
    uint_least8_t age;
    Gender gender;
    uint_least64_t contact_number;
};

std::ostream & operator<<(std::ostream & os, PersonalInformation const & info) {
    os << "PERSONAL INFORMATION\n\n"
       << "NAME: " << info.name << "\nAge: " << info.age
       << "\nGender: " << info.gender << "\nContact no: " << info.contact_number
       << '\n';
    return os;
}

PersonalInformation prompt_user_for_personal_information() {
    PersonalInformation info;
    std::cout << "ENTER PERSONAL INFORMATION:\n\n"
              << "NAME: ";
    std::getline(std::cin, info.name);
    std::cout << "Age: ";
    std::cin >> info.age;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Gender: ";
    std::cin >> info.gender;
    std::cout << "Contact no: ";
    std::cin >> info.contact_number;
    return info;
}

int main() {
    auto info = prompt_user_for_personal_information();
    std::cout << info;
}
  • 1

C++

107,158 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator