0

CODE:

#include<iostream>

using namespace std;

struct Emp{
    int empno;
    char name[100];
    char designation[100];
    float basic;
} employee;

int main(){
    
    cout<<"ID: ";
    cin>>employee.empno;
    
    cout<<"Name: ";
    gets(employee.name);
    
    cout<<"Designation: ";
    gets(employee.designation);
    
    cout<<endl;
    cout<<"Details: "<<endl;
    cout<<employee.empno<<endl;
    cout<<employee.name<<endl;
    cout<<employee.designation<<endl;
    
    
    return 0;
}

OUTPUT: https://i.stack.imgur.com/Hkj8i.png

When I run the code, the cursor skips 'gets(employee.name)' and goes to 'gets(employee.designation)'. Can anyone clarify the reason for this behavior and suggest a method to correct it?

saien
  • 5
  • 4
  • 1
    [Never use `gets()`](https://stackoverflow.com/q/1694036/10077)!! – Fred Larson Nov 09 '20 at 16:28
  • The `cin>>employee.empno;` leaves a newline character that gets consumed by the first `gets()` call. – Fred Larson Nov 09 '20 at 16:31
  • Thanks @FredLarson. What do you suggest an alternative for gets()? What are your thoughts on getline()? – saien Nov 09 '20 at 17:18
  • `std::getline()` is good, but note that it will retain the `'\n'` in the string it reads in. You'll probably want to trim that off. And I do suggest that you use `std::string`, not C-style strings. – Fred Larson Nov 09 '20 at 17:27

0 Answers0