This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 7 years ago.
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;
}
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";
...
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);
Related
This question already has answers here:
getline() does not work if used after some inputs [duplicate]
(3 answers)
Closed 1 year ago.
In the following code, I have made two classes, the second class is inherited from the first one. However when I call the getdata function. it skips input, I have tried using cin.ingnore() and also cin>>ws, but I am still getting the same errors. It runs properly till " Enter the Last name" but after that, it just prints all the other things without taking the input.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class RegistrationModule{
protected:
string Firstname;
string Lastname;
double cnic;
double contact;
string address;
static double challanno;
public:
RegistrationModule(){
Firstname = "";
Lastname = "";
cnic=0;
address = "";
contact=0;
challanno++;
}
};
double RegistrationModule::challanno=105487;
class monthlyentry : public RegistrationModule{
public:
void getdata(){
cout<<"Enter First Name"<<endl;
getline(cin,Firstname);
cin.ignore();
cout<<"Enter Last Name"<<endl;
getline(cin,Lastname);
cin.ignore();
cout<<"Enter your CNIC: "<<endl;
cin>>cnic;
cin.ignore();
cout<<"Enter your Address: "<<endl;
getline(cin,address);
cout<<"Enter your contact number: "<<endl;
cin>>contact;
cout<<"Your Challan Number is: "<<challanno<<endl;
}
};
int main(){
int size;
monthlyentry a;
a.getdata();
}
You cannot just slap ignore() randomly and expect things to work. By default, ignore() will remove 1 character. If there is no character there, it will set eof() bit and your stream cannot read anything more until you clear() eof flag from it.
Only use ignore() when there is a leftover end of line (like after formatted extraction).
void getdata(){
cout<<"Enter First Name"<<endl;
getline(cin,Firstname);
cout<<"Enter Last Name"<<endl;
getline(cin,Lastname);
cout<<"Enter your CNIC: "<<endl;
cin>>cnic;
cin.ignore();
cout<<"Enter your Address: "<<endl;
getline(cin,address);
cout<<"Enter your contact number: "<<endl;
cin>>contact;
cin.ignore(); // might want to clear up before next extractions
cout<<"Your Challan Number is: "<<challanno<<endl;
}
To use std::ws, you would need to use directly in getline calls
std::getline(std::cin >> std::ws, Firstname);
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
So I made this to try understanding classes and this error keeps coming up where in the command prompt tab, it doesn't ask the user to input the next required input when an integer is being asked. I added a comment in the code below for you to know where the error arises from.
#include <iostream>
using namespace std;
class Anime
{
public:
string Name;
int Year;
string Genre;
Anime(string aName, int aYear, string aGenre)
{
Name = aName;
Year = aYear;
Genre = aGenre;
}
};
int main()
{
string aniName;
int aniYear;
string aniGenre;
// This asks for the year
cout << "Anime Year: ";
cin >> aniYear;
// The "Anime Name" line runs but the input for aniName is not asked and skips to the next input
cout << "Anime Name: ";
getline(cin, aniName);
cout << "Anime Genre: ";
getline(cin, aniGenre);
Anime Anime1(aniName, aniYear, aniGenre);
cout << Anime1.Name << endl;
cout << Anime1.Year << endl;
cout << Anime1.Genre << endl;
}
When i make the integer the last input, it works perfectly, but at if I don't want it to be the last one. In that case, what do I do? Any answer is greatly appreciated.
Try to add #include <string>
And add below code upper the input code.
cin >> aniYear;
// The "Anime Name" line runs but the input for aniName is not asked and
skips to the next input
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Anime Name: ";
getline(cin, aniName);
This question already has an answer here:
How to make cin work after using getline?
(1 answer)
Closed 3 years ago.
This program is a small hospital management program.
It works with C++ and uses binary files and classes.
it is a simple prog that taken the input of patients details and saves in a binary file, and displays the patients details by searching regno.
The code does not run beyond : cin>>A1.PI.age; and starts printing endless loop of something.
PLEASE REPLY ME ON WHERE HAVE I GONE WRONG
here is the code:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<stdlib.h>
class all
{ private:
struct address
{ int house;
char street[30];
char city[30];};
struct patient_info
{ char name[40];
address AD1;
int age;
int maritalstatus;
int regno;
char bldgrp[3];
char sex;
}PI;
int task;
protected:
void firstpinfo();
void showpinfo();
void enterpinfo();
public:
void tasks();
char ch;
int serial;
}A1;
class date :public all
{ private :
int day;
int month;
int year;
public:
void enterdate()
{cout<<"enter day of date";
cin>>day;
cout<<"enter month";
cin>>month;
cout<<"enter year";
cin>>year;
}
void showdate()
{ cout<<day<<"/"<<month<<"/"<<year;}
}D1;
//global variables
int count,attempt;
void main()
{ count=0;
cout<<" HOSPITAL MANAGEMENT SOFTWARE
";
D1.enterdate();
A1.tasks();
getch();
while(count==0)
{ A1.tasks();
cout<<"press 0 to continue and 1 to exit";
cin>> count;
}
getch();
}
void all::tasks()
{ attempt=0;
D1.showdate();
cout<<"select task"<<endl
<<"1.show patient details"<<endl
<<"2.enter details of a patient"<<endl
<<"3.exit prog"<<endl;
cin>>task;
switch(task)
{
case 1: {cout<<"enter regno to display"<<endl;
int search;
cin>>search;
fstream fon;
fon.open("hospital.dat",ios::in|ios::binary);
if(!fon)
{cout<<"error in opening"<<endl;
getch();
exit(0);
}
else
{fon.read((char*)&A1,sizeof(A1));
if(A1.PI.regno==search)
{cout<<"showing details";
A1.showpinfo();}
else
{cout<<"regno not found";}
fon.close();
}
break;}
case 2: {cout<<"adding a new patient";
A1.enterpinfo();
fstream fan;
fan.open("hospital.dat",ios::in|ios::binary);
if(fan)
{fan.write((char*)&A1,sizeof(A1));}
fan.close();
break;}
case 3: { cout<<"exiting...press any key";
getch();
exit(0);
break;
}
default: {cout<<"error... press anykey to try again";
getch();
A1.tasks();
};
}}//END OF TASKS
void all::showpinfo()
{cout<<"patient regno\n"<<A1.PI.regno<<endl;
cout<<"patient name\n"<<A1.PI.name<<endl;
cout<<"address of patient\n"<<A1.PI.AD1.house<<" "<< PI.AD1.street<<" "<<PI.AD1.city<<endl;
cout<<"blood group"<<A1.PI.bldgrp<<endl;
cout<<"sex"<<A1.PI.sex<<endl;
cout<<"data extracted";
}
void all:: enterpinfo()
{
cout<<"enter unique registration number";
cin>>PI.regno;
cout<<"enter patient name"<<endl;
cin.getline(A1.PI.name,50);
cout<<"enter address( house, street, city)"<<endl;
cin>>A1.PI.AD1.house;
cin.getline(A1.PI.AD1.street,30);
cin.getline(A1.PI.AD1.city,30);
cout<<"enter age in years"<<endl;
cin>>A1.PI.age;
cout<<"enter 1 for married and 0 for otherwise"<<endl;
cin>>A1.PI.maritalstatus;
cout<<"enter blood group"<<endl;
cin>>A1.PI.bldgrp;
cout<<"enter M for male and F for female";
cin>>A1.PI.sex;
}
why this happens :
This happens because you have mixed cin and cin.getline.
when you enter a value using cin, cin not only captures the value, it also captures the newline. So when we enter 2, cin actually gets the string ā2\nā. It then extracts the 2 to variable, leaving the newline stuck in the input stream. Then, when getline() goes to read the input, it sees ā\nā is already in the stream, and figures we must have entered an empty string! Definitely not what was intended.
old solution :
A good rule of thumb is that after reading a value with cin, remove the newline from the stream. This can be done using the following :
std::cin.ignore(32767, '\n'); // ignore up to 32767 characters until a \n is removed
A better solution :
use this whenever you use std::getline() to read strings
std::getline(std::cin >> std::ws, input); // ignore any leading whitespace characters
std::ws is a input manipulator which tell std::getline() to ignore any leading whitespace characters
source : learncpp website
goto section (Use std::getline() to input text)
hope this is helpful
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
don't use .h extension
we don't think we need #include<conio.h> anymore
and isn't simpler
getline(cin, A1.PI.name) than cin.getline(A1.PI.name,50)
then resize its max size
A1.PI.name.resize(50);
I have the following simple program, but the last line of code getline(cin, topicClass) is never excuted. However, if I use normal cin>>topicClass that is executed. Could you please help me out of this? Thanks
#include <iostream>
#include <string>
using namespace std;
void InfoInput()
{
string classID;
string teacherName;
int totalStudent;
string topicClass;
cout<<"Enter class ID"<<endl;
getline(cin, classID);
cout<<"Enter teacher's name"<<endl;
getline(cin, teacherName);
cout<<"Enter total number of students"<<endl;
cin>>totalStudent;
cout<<"Enter topic of class"<<endl;
getline(cin, topicClass);
//cin>>topicClass;
}
int main ()
{
InfoInput();
}
Your problem is above, with this line:
cin>>totalStudent;
This does not read a line. You enter your input and (I assume) you press ENTER. The \n remains in the buffer of std::cin and is read as an empty line with your next instruction:
getline(cin, topicClass);
To fix, use this code:
cin>>totalStudent;
while(std::isspace(cin.peek())
cin.ignore();
cout<<"Enter topic of class"<<endl;
getline(cin, topicClass);
There is \n remained in cin after reading totalStudent as integer so you need to get that \n first out of the system and then read the next string
#include <iostream>
#include <string>
using namespace std;
void InfoInput()
{
string classID;
string teacherName;
int totalStudent;
string topicClass;
cout<<"Enter class ID"<<endl;
getline(cin, classID);
cout<<"Enter teacher's name"<<endl;
getline(cin, teacherName);
cout<<"Enter total number of students"<<endl;
cin>>totalStudent;
cout<<"Enter topic of class"<<endl;
getline(cin,topicClass);
getline(cin, topicClass);
//cin>>topicClass;
}
int main ()
{
InfoInput();
}
Your classID and teacherName are local variables and disappear after execution leaves the function. You'll have to figure out some way, like passing parameters by reference, to share the variables between functions.
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 8 years ago.
Greetings fellas;
So after i compile the following code ,the MusicIns.shortDescription object don t want to receive any input and just switching to the next object ,what id wrong in my code ?
#include <iostream>
using namespace std;
class Instruments{
public :
int weight;
string size;
string name;
string shortDescription;
string designation;
};
int main(){
Instruments MusicIns;
cout<<"Please enter instrument name: "<<endl;
getline(cin, MusicIns.name);
cout<<"Please enter the size"<<endl;
getline(cin, MusicIns.size);
cout<<"Please enter the weight: "<<endl;
cin>>MusicIns.weight;
cout<<"Please enter a small description: "<<endl;
getline(cin, MusicIns.shortDescription);
cout<<endl;
cout<<"Please describe the instrument designation: "<<endl;
getline(cin, MusicIns.designation);
cout<<endl;
cout<<"============="<<endl;
cout<<MusicIns.name <<endl;
cout<<MusicIns.weight <<endl;
cout<<MusicIns.designation <<endl;
cout<<MusicIns.shortDescription <<endl;
cout<<MusicIns.size <<endl;
return 0;
};
Don t blame me too much for my level or syntax i am still noob.
P.s. Thank you in advance for any help !
After cin>>MusicIns.weight;, there is a newline remaining in the stream. So the new line will be assigned to the MusicIns.shortDescription. Add this line to ignore the newline:
cin.ignore(100, '\n'); before std::getline(std::cin, MusicIns.shortDescription);
One way you can do have "MusicIns.shortDescription" to receive an input is to do this method.
cin.get();
This method will catch any characters after you have terminated from the input.
cout<<"Please enter instrument name: "<<endl;
getline(cin, MusicIns.name);
cout<<"Please enter the size"<<endl;
getline(cin, MusicIns.size);
cout<<"Please enter the weight: "<<endl;
cin>>MusicIns.weight;
cout<<"Please enter a small description: "<<endl;
std::getline(std::cin, MusicIns.shortDescription);
cin.get();// new line
cout<<endl;
cout<<"Please describe the instrument designation: "<<endl;
getline(cin, MusicIns.designation);
cin.get();// new line
cout<<endl;