Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my while loop ending?

It doesn't matter whether I put Y or N, my program ends after I answer "More meat?" I'm expecting it to return the response to the loop.

#include <iostream>
using namespace std;
int main()
{
    char response = 'y';
    double price;
    double total = 0;
    while (response == 'Y' || 'y') {

        cout << "Please enter price of meat: ";
        cin >> price;

        total += price;

        cout << "More meat? (Y/N)";
        cin >> response;
        return response;
    }
    cout << "Your total is: " << total;

    return 0;

}
like image 973
user3169700 Avatar asked Feb 15 '23 04:02

user3169700


2 Answers

while (response == 'Y' || 'y') {

should be

while (response == 'Y' || response ==  'y') {

Also

return response;

exits the whole function (main). You don't need it.


I'm expecting it to return the response to the loop

You don't need to ( return is used for returning a value from a function, terminating its execution). So, after } of the loop, the next executed line will be while ( condition ) .... If condition is evaluated to false, the loop will stop and the next executed line will be the one, after the loop's }.

like image 153
Kiril Kirov Avatar answered Feb 18 '23 12:02

Kiril Kirov


Your indentation is broken, as is your while() test and you have a spurious return statement:

#include <iostream>
using namespace std;
int main()
{

    char response = 'y';
    double price;
    double total = 0;
    while (response == 'Y' || response == 'y') {

        cout << "Please enter price of meat: ";
        cin >> price;

        total += price;

        cout << "More meat? (Y/N)";
        cin >> response;
    } // end while
    cout << "Your total is: " << total;

    return 0;
} // end main()

(Using do ... while() would be slightly neater as well as you wouldn't need to initialize response to 'y').

like image 40
trojanfoe Avatar answered Feb 18 '23 12:02

trojanfoe