need help with loop

Question:
i have this do while loop for when i enter a number. right now i have the value of 10 to quit the loop but that was only temporary to see if my project compiled. can some one help me with the loop if you can figure out away so that i can end the loop with out using a number that would be great because when i use the number it adds that number to my list and i dont want that. also i think a while loop would work better but i couldnt get it to work.

[code]
do
{
std::cout<<"enter a number or list of numbers when done enter type 10"<<std::endl;
std::cin>>num;



stats.setCount();
stats.setSum(num);
stats.setMean(num);
stats.setMin(num);
stats.setMax(num);
stats.setLast(num);


}while(num != 10);

You may be able to cheat it by using an if statement inside the loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
do
{
std::cout<<"enter a number or list of numbers when done enter type 10"<<std::endl;
std::cin>>num;


if (num != 10)
{
stats.setCount();
stats.setSum(num);
stats.setMean(num);
stats.setMin(num);
stats.setMax(num);
stats.setLast(num);
}

}while(num != 10); 


Then it won't add it to the list?
Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    int num = 0;
    
    while(std::cout << "Please enter a number (10 or any character to quit): " and std::cin >> num and num != 10){
        std::cout << "Number is: " << num << '\n';
    }
    
    // REPAIR STREAM
    std::cin.clear();
    std::cin.ignore(1000, '\n');
    
    std::cout << "Exited\n";
    
    return 0;
}
Please enter a number (10 or any character to quit): 1
Number is: 1
Please enter a number (10 or any character to quit): 2
Number is: 2
Please enter a number (10 or any character to quit): 3
Number is: 3
Please enter a number (10 or any character to quit): s
Exited
Program ended with exit code: 0


By typing in a character cin is deliberately put in error so when you exit the loop that error needs to be corrected as shown before cin can be reliably used.

BTW It's probably obvious but while do vs do while is the way to go here.
Last edited on
The easiest way is to use break in order to jump out of a while(true) loop.

1
2
3
4
5
6
7
8
9
10
while(true)
{
    std::cin >> num;
    if(num == 10)
    {
        break;
    }

    // do stuff
}
Topic archived. No new replies allowed.