Answer the question
In order to leave comments, you need to log in
Why is cin skipping?
Why is the input skipped by the >> operator?
Program code snippet:
Person *pPersonArray[5];
for (int i = 0; i < 5; i++)
{
Person *pDynPerson = new Person("Dinamyc", "Person", 10, Male);
PrintPerson(*pDynPerson);
ReadPerson(pDynPerson);
PrintPerson(*pDynPerson);
delete pDynPerson;
}
#pragma once
#include <iostream>
#include <string>
#include "Sex.h"
struct Person
{
std::string fName, lName;
int age;
Sex sex;
Person(std::string firstName = "", std::string lastName = "", int Age = 0, Sex Sex = Male)
{
fName = firstName;
lName = lastName;
age = Age;
sex = Sex;
}
};
void PrintPerson(Person& person);
void ReadPerson(Person* person);
#include "Person.h"
void PrintPerson(Person& person)
{
std::cout << person.fName << '\t' << person.lName << "\t Age:" << person.age << "\t Sex:" << SexToStr(person.sex) << std::endl;
}
void ReadPerson(Person* person)
{
std::cout << "\nEnter person first name:";
std::cin >> person->fName;
std::cout << "\nEnter person last name:";
std::cin >> person->lName;
std::cout << "\nEnter person age:";
std::cin >> person->age;
std::cout << "\nEnter person sex(Male,Female):";
std::cin >> person->sex;
}
Answer the question
In order to leave comments, you need to log in
Judging by your log, it broke into: "Enter person sex(Male,Female):Male"
Since the Sex type is a user type, an overload of the >> operator is defined for it. The Sex.h file you didn't show should declare something like:
std::istream& operator>>(std::istream& stream, Sex &sex)
and read and process the entered value correctly (i.e. .strings "Male" or "Female" and the corresponding filling of the object sex)
Well, offhand, something like this:
std::istream& operator>>(std::istream& stream, Sex &sex)
{
std::string s;
stream >> s;
if (s.compare("Male") == 0)
sex = Male;
else (s.compare("Female") == 0)
sex = Female;
else
sex = Unknown;
return stream;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question