How can I stop cin from skippping a line? [duplicate] - c++

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
cin and getline skipping input [duplicate]
(4 answers)
Closed last year.
I was trying to make a program where the user is asked to give an input and it gives output with answered questions. Everything looks alright except that cin skipped my last question about school.
This is the original code:
//this program fills my data in profile
#include <iostream>
#include <string>
using namespace std;
int main () {
int age, exp_years;
char desired_grade;
string school_name, name;
const int year_grad = 4;
bool is_student;
cout << "You will need to enter your data for portfolio card" << endl;
cout << "Enter your last name" << endl;
cin >> name;
cout << "Enter your age" << endl;
cin >> age;
cout << "Enter your years of work experience" << "\n";
cin >> exp_years;
cout << "Is it true or false that you are a student (put 'true' or 'false')" << endl;
cin >> is_student;
cout << "Great! What school are you in (if you are not a student put desirable school)?" << endl;
cin >> school_name;
/* trying to make a function below */
cout << "Awesome, here is your info" << endl << "Your last name is "<< name << endl <<"You are "<<age << " years old." << endl << exp_years << " years of work experience" << endl;
if ( is_student == 1)
{
cout << school_name << " is lucky to have you!\n";
return 0;
} else {
cout << "Btw I am sure that " << school_name << " would be happy to have you as their student anytime\n";
return 0;
}
return 0;
}
I read some article and they said that getline() can help, so I tried to substitute with:
cout << "Is it true or false that you are a student (put 'true' or 'false')" << endl;
getline(cin, is_student);
cout << "Great! What school are you in (if you are not a student put desirable school)?" << endl;
getline(cin, school_name);
Hovewer, it gives me an error:
error: no matching function for call to 'getline'
What am I missing?

It seems the problem is related to entering a boolean value.
Here is shown how to enter boolean values
#include <iostream>
#include <iomanip>
int main()
{
bool is_student;
std::cin >> is_student; // accepts 1 as true or 0 as false
std::cout << is_student << '\n';
std::cin >> std::boolalpha >> is_student; // accepts strings false or true
std::cout << is_student << '\n';
}

Related

I'm writing simple struct program and the getline returns empty string [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
getline not working properly ? What could be the reasons? [duplicate]
(3 answers)
getline not asking for input? [duplicate]
(3 answers)
cin and getline skipping input [duplicate]
(4 answers)
Closed 4 months ago.
I'm collage student and I'm trying to do simple struct program
I wrote this code then the second getline returns empty string.
#include <iostream>
#include <string>
using namespace std;
struct person
{
string name;
string phone;
int age;
float salary;
};
int main()
{
person p1;
cout << "Enter your name : ";
getline(cin, p1.name);
cout << "Enter your age : ";
cin >> p1.age;
cout << "Enter your phone number : ";
getline(cin, p1.phone);
cout << "Enter your salary : ";
cin >> p1.salary;
cout << "------------------------------------------------------------\n";
cout << "Your personal information : \n";
cout << "Name : " << p1.name << endl;
cout << "Age : " << p1.age << endl;
cout << "Phone number : " << p1.phone << endl;
cout << "Salary : " << p1.salary << endl;
return 0;
}
I though it was from the IDE but when I tried it on deferent IDE on deferent device I got the same result

How to make getline command work in a while loop? [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 3 years ago.
I use getline command in a while loop. The command works fine in the first loop. But after the second loop, it just passes the getline commands and doesn't allow me to enter
I tried cin.get and cin.getline but the problem is not fixed
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int price;
void addItem(){
string product;
cout << "Please enter product's name: " << endl;
getline(cin, product);
cout << "Please enter product's price: " ;
cin >> price;
cout << "You have added " << product << " with a price of $" << price << " to your cart." << endl;
}
int main() {
char answer = 'y';
int total = 0;
while (answer == 'y'){
addItem();
total += price;
cout << "Do you want to add another product (y/n)? " ;
cin >> answer;
}
if (answer != 'y'){
cout << "Your total is $" << total << endl;
}
return 0;
}
Mixing cin >> with getline(cin,...), so you should to avoid it. I assume that you used getline to read product name which contain spaces inside. You could rewrite your code to use only getline which should give you expected behavior:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int price = 0;
void addItem(){
string product{};
string price_str{};
cout << "Please enter product's name: " << endl;
getline(cin, product);
cout << "Please enter product's price: " ;
getline(cin,price_str);
/*CHECK IF price_str is number before calling stoi*/
price = stoi(price_str);
cout << "You have added " << product << " with a price of $" << price << " to your cart." << endl;
}
int main() {
string answer = "y";
int total = 0;
while (answer == "y"){
addItem();
total += price;
cout << "Do you want to add another product (y/n)? " ;
getline(cin,answer);
}
if (answer != "y"){
cout << "Your total is $" << total << endl;
}
return 0;
}
try
while(cin>>answer && answer !='y'){
cout<<"enter again \n";
}
cout<<"ok";

Run time error of cin.get() [duplicate]

This question already has answers here:
Using getline(cin, s) after cin [duplicate]
(13 answers)
Closed 5 years ago.
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
void cpp_string();
void cstyle_string();
int main()
{
cpp_string();
cstyle_string();
system("pause");
return 0;
}
void cpp_string()
{
string fName, lName;
char grade;
int age;
cout << "What is your first name?";
getline(cin, fName);
cout << "What is your last name?";
getline(cin, lName);
cout << "What letter grade do you deserve?";
cin >> grade;
cout << "What is your age?";
cin >> age;
cout << "Name: " << fName << ", " << lName << endl;
cout << "Grade: " << grade << endl;
cout << "Age: " << age << endl;
return;
}
void cstyle_string()
{
char fNm[20], lNm[20];
char grade;
int age;
cout << "What is your first name?";
cin.get(fNm, 20).get();
cin.clear();
cout << "What is your last name?";
cin.get(lNm, 20).get();
cout << "What letter grade do you deserve?";
cin >> grade;
cout << "What is your age?";
cin >> age;
cout << "Name: " << fNm << ", " << lNm << endl;
cout << "Grade: " << grade << endl;
cout << "Age: " << age << endl;
return;
}
I'm getting output as
What is your first name?demiurge conon
What is your last name?no
What letter grade do you deserve?a
What is your age?22
Name: demiurge conon, no
Grade: a
Age: 22
What is your first name?What is your last name?What letter grade do you deserve?What is your age?Name: ,
Grade: ╠
Age: -858993460
Press any key to continue . . .
but if I run cstyle_string() in different file then I'm not getting any errors code works perfectly.
I want to know why this is happening?
There are two question.
Redundant \n
the state of cin
The last cin in cpp_string is cin >> age.
It will leave a \n not extracted.
In first of cstyle_string is cin.get(fNm, 20).get();
The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream
the cin.get(FNm, 20) will parse empty input before \n, and no characters are available in the stream in actually. In this case, the failbit flag will be set and next all cin >> operator will fail.
You can only call cstyle_string and press enter directly, the same thing will happen.

Why Is My Program Skipping The cin > > after the first cycle of the For Loop?

My program runs the first For loop correctly then skips the Cin's on the 2nd and 3rd cycle. Then when the loop is finished it goes on to calculate the BMI of the first index [0] and does this correctly and gives the right answer but then nothing for the index's 1 and [2] because no information was inputted because the cin's were skipped.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Patient
{
double height;
double weight;
int age;
bool isMale;
};
int main()
{
Patient Patients[3];
for (int i = 0; i < 3; i++) {
cout << "Patient "<< i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << endl << endl;
}
cout << endl << endl;
for (int i = 0; i < 3; i++) {
float BMI = Patients[i].weight / (Patients[i].height *Patients[i].height);
cout << "Patient " << i << " Has A BMI of: " << BMI << endl << endl;
}
return 0;
}
This is the console where you can see after the first loop all the cin's are skipped but the first loop was correctly stored as it couted the BMI of the first index:
You see that you are having an error at the end of the loop. You can see from iterations 2 and 3 that cin is not behaving the same way each time. There are a couple of error state flags that come from ios that will help you see what's going wrong here. See iso::good for details. If you add those checks:
for (int i = 0; i < 3; i++) {
cout << "Patient " << i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << cin.good() << '\n';
cout << cin.eof() << '\n';
cout << cin.fail() << '\n';
cout << cin.bad() << '\n';
cout << endl << endl;
}
What you will see if that cin is no longer good, it is not eof it is fail, and it is not bad. While the fail bit is set, cin will not work. Hence you see the result. Looking at the chart in the link you see this:
Logical error on i/o operation
You were preforming an i/o operation of inserting "true" into a bool. The word true is probably stored as a character array or string, not a boolean. How should cin convert this to a boolean? You need to trap your input and convert it into a bool or switch to use an input that can be explicitly converted into a bool.
For example:
cout << "Is Patient " << i << " Male? (1 for Male, 0 for Female):";
cin >> Patients[i].isMale;
In this case the cin recognizes 1 and 0 as integers and can convert an integer into a boolean. 0 is false, everything else is true. Another option is to let the library do it and use boolalpha. You can read about it here.
This shows a larger issue. What happens if I write "two point five" as the answer to height? In this case we can assume some intelligence on the part of the user, but thinking about things like this will help write more robust code in the future.
You can fix your program in two ways.
Just input "0" or "1" in the male/female question instead of "true" or "false".
Change this line and continue to input "true" or "false":
cin >> boolalpha >> Patients[i].isMale;
Sources:
Cin and Boolean input
http://www.cplusplus.com/reference/ios/boolalpha/

C++ loop error that my professor can't figure out

I am currently taking a C++ programming class and am working on a project in which I have to create a fairly simple movie database. My code essentially works as intended yet in certain cases it causes the main menu to loop infinitely and I cannot figure out why. I brought this to my teacher and he cannot explain it either. He gave me a workaround but I would like to know if anyone can see the cause of the problem. Full code is as follows:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct MovieType
{
string title;
string director;
int year;
int length;
string rating;
};
MovieType addMovie() {
MovieType newMovie;
cout << "Movie title :";
getline(cin, newMovie.title);
cout << "Director :";
getline(cin, newMovie.director);
cout << "Year :";
cin >> newMovie.year;
cout << "Length(in minutes) :";
cin >> newMovie.length;
cout << "Rating :";
cin >> newMovie.rating;
cout << endl;
return newMovie;
}
void listMovie(MovieType movie) {
cout << "______________________________________" << endl;
cout << "Title : " << movie.title << endl;
cout << "Director : " << movie.director << endl;
cout << "Released : " << movie.year << endl;
cout << "MPAA Rating : " << movie.rating << endl;
cout << "Running time : " << movie.length << " minutes" << endl;
cout << "______________________________________" << endl;
}
void search(vector<MovieType> movieVector) {
string strSearch;
cout << endl << "Search title: ";
getline(cin, strSearch);
for (int c = 0; c < movieVector.size(); c++) {
if (movieVector.at(c).title == strSearch)
listMovie(movieVector.at(c));
}
}
int main() {
bool quit = 0;
vector<MovieType> movieVector;
while (quit == 0) {
char selection = 'f';
cout << "Main Menu:" << endl;
cout << "'a' - Add movie" << endl;
cout << "'l' - List movies" << endl;
cout << "'s' - Search by movie title" << endl;
cout << "'q' - Quit" << endl;
cout << "Please enter one of the listed commands:";
cin >> selection;
cin.ignore();
cout << endl;
if (selection == 'a')
movieVector.push_back(addMovie());
else if (selection == 'l') {
for (int c = 0; c < movieVector.size(); c++) {
listMovie(movieVector.at(c));
}
}
else if (selection == 's') {
search(movieVector);
}
else if (selection == 'q')
quit = 1;
}
return 0;
}
When an unexpected input type is entered during the addMovie function(like entering text for the int type year), it just runs through the function then loops through the menu infinitely. It appears to me that the code just stops even looking at the input stream. I have tried using cin.ignore() in many different places but it doesn't matter if there is nothing left in the stream it just keeps going.
I am using NetBeans to compile my code.
I really have no idea why it behaves like this otherwise I would offer more information but I am just curious as to why this happens, because as I said before, my professor doesn't even know why this is happening.
Any help or insight is greatly appreciated.
cin enters an error state where cin.fail() is true. In this state it just ignores all input operations. One fix is to clear the error state, but better, only use getline operations on cin, not formatted input.
E.g., instead of
cin >> newMovie.year;
… do
newMovie.year = stoi( line_from( cin ) );
… where line_from can be defined as
auto line_from( std::istream& stream )
-> std::string
{
std::string result;
if( not getline( stream, result ) )
{
// Throw an exception or call exit(EXIT_FAILURE).0
}
return result;
}
Disclaimer: code untouched by compiler.