Can't spaces be used in a row? C ++

I mainly experiment with polymorphism. I have 2 objects, a client and an employee. the customer has a name and complaint. The employee has a name and salary.

In a loop, I take these parameters and create a new Person to add to the array.

But here is my problem: if I put spaces in a line, the loop ends to the end.

Person *persons[10];

for (int i = 0; i < sizeof persons;i++)
{
    cout<<"Please type 1 for customer or 2 for Employee"<<endl;
    int q;
    cin>>q;
    string name;
    int salary;
    string complaint;


    if (q == 1)
    {
        cout<<"What is your name?"<<endl;
        cin>>name;
        cout<<"What is your complaint"<<endl;
        cin>>complaint;

        personPtr = new Customer(name,complaint);
        cout<<"Created customer"<<endl<<endl;
        persons[i] = personPtr;
        cout<< "added to array"<<endl<<endl;
    }
    else if(q==2)
    {
        cout<<"What is your name?"<<endl;
        cin>>name;
        cout<<"What is your salary"<<endl;
        cin>>salary;
        personPtr = new Employee(name,salary);
        persons[i] = personPtr;
    }
    else
    {
        cout<<"Sorry but i could not understand your input. Please try again"<<endl;
        i--;
        cin>>q;
    }
}
delete personPtr;
system("PAUSE");

Is there any special way to include strings?

Customer and employee classes are listed here.

class Person
{
public:
Person(const string n)
{name = n;}; // initialise the name
virtual void printName();
protected:
string name;
};


class Customer:public Person
{
public:
string complaint;

Customer(string name, string cm)
    :Person(name)
{       
    complaint=cm;
}
virtual void printName();
};

class Employee:public Person
{
public:
int salary;

Employee(string name,int sl)
    :Person(name)
{       
    salary = sl;
}
virtual void printName();
};
+3
source share
3 answers
  • Input operator

    std::istream& operator>>(std::istream& is, std::string&)
    

    only ever reads input to the next space character . (This is exactly as it was pointed out when Jerry Schwartz invented IO streams 25 years ago.) If you need to read whole lines, then

    std::istream& getline(std::istream&, std::string&, char='\n')
    

    - , :

    std::string name;
    std::getline(std::cin, name);
    
  • . , int , . , , . . >> .
    , , . - :

    if(!std::cin) {
      // input failed
    }
    
+8

, sizeof . (. )

cin . , "" "". , .

+1

@sbi already answered your main question. But there are a few more things you can pay attention to.

  • You hold pointers after they are deleted, which can cause problems later.
  • Instead system("PAUSE")you should use _getch()or cin.get(). Using system calls to open an open command window is not ideal.
+1
source

Source: https://habr.com/ru/post/1791995/


All Articles