Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String input in standard C++ [duplicate]

Tags:

c++

string

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;
}

2 Answers

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";
...
like image 59
ixSci Avatar answered Sep 26 '26 08:09

ixSci


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);
like image 27
Graeme Avatar answered Sep 26 '26 06:09

Graeme