3

I want to take string input this C++ program but the following code doesn't work. It doesn't take the employee's name as input. It just skips. Sorry I am new to C++.

#include<iostream>
#include<string>
using namespace std;
int main()
{
  int empid;
  char name[50];
  float sal;
  cout<<"Enter the employee Id\n";
  cin>>empid;
  cout<<"Enter the Employee's name\n";
  cin.getline(name,50);
  cout<<"Enter the salary\n";
  cin>>sal;
  cout<<"Employee Details:"<<endl;
  cout<<"ID : "<<empid<<endl;
  cout<<"Name : "<<name<<endl;
  cout<<"Salary : "<<sal;
  return 0;
}
graham.reeds
  • 15,267
  • 16
  • 66
  • 133
  • [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline). But mixing use of `std::cin >> foo` with either form of `getline` is tricky, and best avoided, because they treat newline characters differently, and confuse each other. I find it best to read a line at a time, then process each line within your program. – BoBTFish Jan 25 '16 at 12:11
  • Thank you for the answer . Could you tell me why the cin.getline() syntax doesn't work? –  Jan 25 '16 at 12:12
  • 4
    `std::cin.getline()` requires you to manage a buffer yourself, which is always trickier. What if your user has a long name, for instance? `std::string name; std::getline(std::cin, name);` handles this for you. As to why you current version doesn't work: `cin>>empid` leaves a trailing `\n` character on the stream, which `getline` sees *before* it sees the name. So you read the end of the previous line, instead of the line you actually wanted. Don't mix the two ways of reading, it's a PITA. – BoBTFish Jan 25 '16 at 12:16

2 Answers2

3

You need to skip a \n character which is left in the input buffer after the following line execution: cin >> empid;. To remove this character you need to to add cin.ignore() after that line.

...
cout << "Enter the employee Id\n";
cin >> empid;
cin.ignore();
cout << "Enter the Employee's name\n";
...
ixSci
  • 10,620
  • 5
  • 35
  • 66
2

The cin>>empid is leaving the carriage return in the input stream, this is then being picked up as soon as the cin.getline method is called so it is exiting immediately.

If you read one character before the getline your code works, although this is probably not the nicest way to resolve the issue :)

cout<<"Enter the employee Id\n";
cin>>empid;
cout<<"Enter the Employee's name\n";
cin.get();
cin.getline(name,50);
Graeme
  • 1,413
  • 11
  • 23