Ad

How Can I Stop Cin From Skippping A Line?

- 1 answer

So 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 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?

Ad

Answer

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';
}
Ad
source: stackoverflow.com
Ad