How JustAnswer Works:

  • Ask an Expert
    Experts are full of valuable knowledge and are ready to help with any question. Credentials confirmed by a Fortune 500 verification firm.
  • Get a Professional Answer
    Via email, text message, or notification as you wait on our site.
    Ask follow up questions if you need to.
  • 100% Satisfaction Guarantee
    Rate the answer you receive.

Ask Leela-TheProgrammer Your Own Question

Leela-TheProgrammer
Leela-TheProgrammer, Computer Software Engineer
Category: Programming
Satisfied Customers: 474
Experience:  Post Grad in CS (Gold Medal)
21067471
Type Your Programming Question Here...
Leela-TheProgrammer is online now
A new question is answered every 9 seconds

How do i get a while loop to reprompt the user cin following

Customer Question

how do i get a while loop to reprompt the user for a cin for the following code if there is an invalid input in year1 such as a string? do i have to use cin.fail()? if so, how do i do it?
string month1;
string day1;
int year1;
cout <> month1 >> day1 >> year1;
Submitted: 11 months ago.
Category: Programming
Expert:  Leela-TheProgrammer replied 11 months ago.

Hi,

Thanks for using JustAnswer. This is Leela and I will help you with the question today.

You can use cin.fail() to prompt user for valid input. It can be done as follows.

The below function shows an example of how to get a valid int from user, also prompt till user enter a valid int. You can refer the same and use in your program.

int getValidInt()

{

string invalid_input;

int val;

cin >> val;

while (cin.fail())

{

cout << "You entered a value of the wrong type!" << endl;

cin.clear();

getline(cin,invalid_input);

cout << "Enter a int : " << endl;

cin >> val;

}

return val;

}

Hope this helps.

Please let me know if there are any further queries.

I can help you with any computer science related subjects concepts understanding via one-on-one skype sessions, programs, latest technology happenings, etc.

All the best.

Thanks,

Leela