Exercise:
Write a C++ program using do-while loop that prompts for and inputs a user entry of "Y" or "N". f the user fails to enter a correct value, the loop outputs an error message and then repeats the request for the user to enter a value.

This is what I did and it seems like I did the other way around. (NO BOOLEANS, NO GETLINES). Just Do-While Statement

#include <iostream>
using namespace std;
int main()
{
    char ans = ' ';
    string ques = "Are you 18 years old or above? ";

    do 
    {
           cout<<ques;
           cin>>ans;

            if (ans == 'y'|| ans == 'Y'|| ans == 'N' || ans == 'n')
            {
                    cout<<"VALID LETTER"<<endl;
            }   
            else
            {
                cout<<"INVALID LETTER"<<endl;
            }                  


    }while (ans == 'y'|| ans == 'Y' || ans == 'N' || ans == 'n');

    system("pause");
}

Recommended Answers

All 4 Replies

#include <iostream>
using namespace std;

int main()
{

    char ans = ' ';
    string ques = "Are you 18 years old or above? ";

    do 
    {

           cout<<ques;
           cin>>ans;

            if (ans == 'y'|| ans == 'Y'|| ans == 'N' || ans == 'n')
            {
                cout<<"VALID LETTER"<<endl;
                //you might want to put a `break` keyword here
                //or other to terminate the loop?
            }   
            else
            {
                cout<<"INVALID LETTER"<<endl;
            }

    }while (ans == 'y'|| ans == 'Y' || ans == 'N' || ans == 'n');   
    //you mean
    //while (!(ans == 'y'|| ans == 'Y' || ans == 'N' || ans == 'n'))

    system("pause");
}

Also, you did not type in

#include <string>
commented: Not really required. Most compilers will accept without including string. The user is not doing anything which really requires the library. -1
commented: No reason for the downvote +14

@dominiquehelper: what exactly is the question about the code you posted? Does the code you posted compile and work correctly? If not, why not? Just posting code without an explanation of what you don't understand isn't helpful to any of us -- we are not mind readers.

Here is some good advice for new members. You should read that post.

You say 'no booleans', but why? There are several boolean tests in your code:

if (/* boolean test1 */)
do { ... } while (/* boolean test2 */)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.