wolf_adventures1909 wolf_adventures1909 - 2 months ago 9x
C++ Question

C++ while loop does not function as expected/hoped

I've been programming a little calculator project in C++ just to train my skills (and hopefully give me a sense of achievement), but I'm encountering a problem with my while loop.

Essentially the program prompts the user for the 'mode'/command to use (e.g multiplication, division etc), and then calling the appropriate command. Once they've finished it should bring them back to the start (the while loop which is while true essentially) and start over again (return 0), with the option to quit (return 1). However, it quits instantly after the first time, even though. Am I doing something wrong? Do I seriously misunderstand C++ programming? Or what?
Here is my code: (most functions cut out)

#include <iostream>

using namespace std;

int cMode(); // function prototypes
int add();
int sub();
int mult();
int divide();
int sqr();

int main() { // main function start
do {
} while (0);

return 0;

int cMode() { // mode selection func
int mode;
cout<<"Please select which mode you would like to avail from the following:\n";
cout<<"1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Sqaure root finder\n6. Exit\n";
if ( mode == 1 ) {
return add();

int add() { // addition function
int x, y; // variables

cout<<"Please type the first number to add: ";
cout<<"Please type the second number to add: ";
x = x + y;
cout<<"The answer is "<< x <<".";
return 0;

Anyway, if someone could help would be much appreciated. Also, two further little questions on the line with out<<"...."<< x <<;, why do I have to include the "" at the end for it to run? I was getting an error with them, and why cant I put endl at the end of the "" on a cout line?



Problem is here:

int main() { // main function start
    do {
    } while (0);

It will execute the do {} part and then since condition in while is 0 it exits. do-while executes until the condition evaluates to a non-zero value.

You probably want to create a variable and store the return value from cMode() and then have something like:

int main() { // main function start
    int ret=0;   
    do {
    } while (ret);

By the way, for this to work, you need to make sure that cMode() returns 0 only if user selects mode 6 (Exit).

NVM Edited your question, as that was a code formatting issue: And another thing, maybe it is a question formatting problem but you have your add() function inside the main() and I don't think that works in c++.