fork(1) download
  1. // Class employee
  2.  
  3. #include <iostream>
  4. #include <limits>
  5. #include <cstdio>
  6.  
  7. using std::cin;
  8. using std::cout;
  9. using std::endl;
  10.  
  11. class emp {
  12. int ecode;
  13. char ename[20];
  14. float basic_pay;
  15.  
  16. public:
  17. void input() {
  18. cin >> ecode;
  19. cin.ignore();
  20.  
  21. if (!cin.getline(ename, 20)) // <-- PROBLEM HERE
  22. {
  23. cout << "Name too long, trimmed to: " << ename << endl;
  24.  
  25. // clear the stream error flags and ignore rest of the line
  26. cin.clear();
  27. cin.ignore(std::numeric_limits<int>::max(), '\n');
  28. }
  29.  
  30. // now this line will not fail
  31. cin >> basic_pay;
  32. }
  33. float calc( float x) {
  34. return x+x/10;
  35. }
  36. void output() {
  37. cout << "\n Emp. code: " << ecode;
  38. cout << "\n Emp. name: " << ename;
  39. cout << "\n Emp. basic pay: " << basic_pay;
  40. cout << "\n Emp. net pay: " << calc( basic_pay);
  41. }
  42. };
  43.  
  44. int main() {
  45. emp e1;
  46. cout << "Enter details of employee:\n";
  47. e1.input();
  48. cout << "\nUpdated Profile:\n";
  49. e1.output();
  50. return 0;
  51. }
Success #stdin #stdout 0s 3464KB
stdin
5
Longggggggg Name123456789
6
7
stdout
Enter details of employee:
Name too long, trimmed to: Longggggggg Name123

Updated Profile:

 Emp. code: 5
 Emp. name: Longggggggg Name123
 Emp. basic pay: 6
 Emp. net pay: 6.6