Member Avatar for DigitalPackrat
class Customer {
  
  private:
    
    char name[50];
    int acc_no;   
    char acc_type;
    float balance;
  
  public:
    
    void getData();
};

int main() {
  
  Customer cust;
  cust.getData();  
  cust.getData();
}

void Customer::getData() {

  cout<<"Name : ";
  cin>>name;
  
  cout<<"Acc No. : ";
  cin>>acc_no;
  
  cout<<"Acc Type : ";
  cin>>acc_type;
}

The second time I call the function getData of customer class, I does not ask me for the name. I have tried gets(), cin.getline. Again, the same problem.

Also, how can I prevent input of characters other than numbers in integers, float etc?

Recommended Answers

All 2 Replies

At the end of getData() you need to add code to remove the '\n' from the keyboard buffer. Getting numbers (ints, floats, doubles) has the side affect of cin leaving the Enter key '\n' in the keyboard buffer, so the next time a character string needs to be entered cin appears not to do anything. Narue wrote a very good article about how to flush the input stream in this link.

>>Also, how can I prevent input of characters other than numbers in integers, float etc?
You have to accept them as strings and parse the characters to see if there are any non-numeric digits.

Another method is to call cin.peek() to see if there is anything in the keyboard except '\n'.

int x;
    cout << "Enter a number ... ";
    cin >> x;
    if(cin.peek()  != '\n')
        cout << "bad data\n";
Member Avatar for DigitalPackrat

Great, added cin.clear() and cin.sync().

>>When this works, it works beautifully.
(Narue's comments about cin.sync())
Thankfully it worked.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.