Home > OS >  While Loop In C
While Loop In C

Time:12-21

Guys I Want Help Regarding Code Below, I Want To Add A While Loop In Which A User Keeps Getting The Else Statement's Cout. Until User Satisfies If or Else-If Condition. In Other Words The Program Should Only End When User Writes 'g''G''b''B' Other Wise It Should Keep Showing The Else's Cout With Asking Again To Put The Right Value.

#include <iostream>
using namespace std;

int main()
{
    string item;
    float price;
    int quantity;
    float total;
    char experience;

    cout << "Write The Name Of Item You Want To Buy:" << endl;
    getline(cin, item);

    cout << "What Is The Price Of " << item << " In Dollars $ ?" << endl;
    cin >> price;

    cout << "What Is The Quantity Of " << item << endl;
    cin >> quantity;

    total = price*quantity;

    cout << "Your Total Bill For " << quantity << " " << item << " Is " << total << "$" << endl<< endl;
    
    cout << "How Was Your Shopping Experience Write (G) If Good And (B) For Bad" << endl;
    cin >> experience;

    if (experience == 'g' || experience == 'G')
    {
        cout << "We Appreciate Your Feedback THANKS For Shopping :)";
    }
    else if (experience == 'b' || experience == 'B')
    {
        cout << "Sorry For Bad Experience, We Will Do Better Next Time THANKS For Shopping :)";
    }
    else
    {
        cout << "Write \"G\" If Good And \"B\" If Bad";
    }

CodePudding user response:

Here's the answer, you should prompt for input, then check the input using a while loop instead of IF-ELSE to make sure the user provided the answer you desired. This is actually a simple logic question tho. You may explore do-while loop too.

#include <iostream>
using namespace std;

int main()
{
    string item;
    float price;
    int quantity;
    float total;
    char experience;

    cout << "Write The Name Of Item You Want To Buy:" << endl;
    getline(cin, item);

    cout << "What Is The Price Of " << item << " In Dollars $ ?" << endl;
    cin >> price;

    cout << "What Is The Quantity Of " << item << endl;
    cin >> quantity;

    total = price*quantity;

    cout << "Your Total Bill For " << quantity << " " << item << " Is " << total << "$" << endl<< endl;

    cout << "How Was Your Shopping Experience Write (G) If Good And (B) For Bad" << endl;
    cin >> experience;

    while (experience != 'G' && experience != 'g' && experience != 'B' && experience != 'b') {
        cout << "Write \"G\" If Good And \"B\" If Bad\n";
        cin >> experience;
    } 

    if (experience == 'g' || experience == 'G') {
        cout << "We Appreciate Your Feedback THANKS For Shopping :)";
    } else if (experience == 'b' || experience == 'B') {
        cout << "Sorry For Bad Experience, We Will Do Better Next Time THANKS For Shopping :)";
    }

    return 0;
}
  • Related