0
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?

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by DigitalPackrat
0

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";
0

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

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

Thanks.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.