Prodipto Sarkar Prodipto Sarkar - 2 months ago 6
C++ Question

Why is this code not taking input for "Designation"?

why is this not taking inputs for "Designation"?

As you can see from the screenshot, the

fgets()
function is running only once to take in the string
name
, but it is not accepting the
designation
string and is skipping onto the "salary" input. What is intriguing me even more is the fact that this same code is running perfectly well in TurboC3....I am getting problems only with GCC compiler based IDE such as DevCPP and now in GCC itself in Linux.

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <string.h>
using namespace std;

class emp
{
private:
char name[20], desig[20];
int id;
float salary;

public:
void getdata()
{
cout << "ENTER NAME:\n";
fgets(name, 20, stdin);
cout << "ENTER ID:\n";
cin >> id;
cout << "ENTER DESIGNATION:\n";
fgets(desig, 20, stdin);
cout << "ENTER SALARY:\n";
cin >> salary;
}

void showdata()
{
cout << "NAME:- " << name << "\n";
cout << "ID:- " << id << "\n";
cout << "DESIGNATION: " << desig << "\n";
cout << "SALARY: " << salary << "\n";
}
};

int main()

{

emp ins[3];
int i;
cout << "ENTER DETAILS:\n";
for (i = 0; i < 3; i++)
ins[i].getdata();
cout << "*****************************DETAILS***************************\n";

for (i = 0; i < 3; i++)
ins[i].showdata();
return 0;
}

Answer

Don't Mix C and C++ Input Streams

Either use stdin or istream. In terms, this means to not use both fgets() and cin in the same area. Use one or the other. To read a complete string, with whitespace, use std::getline(std::cin, input)

Comments