while break sample code in c++
时间: 2024-02-24 16:53:33 浏览: 68
Sure! Here's an example of how to use `while` and `break` in C++:
```
#include <iostream>
using namespace std;
int main() {
int num;
while (true) {
cout << "Enter a number: ";
cin >> num;
if (num < 0) {
cout << "Negative numbers are not allowed." << endl;
break;
}
cout << "You entered: " << num << endl;
}
cout << "The loop has ended." << endl;
return 0;
}
```
This code prompts the user to enter a number, and if the number is negative, the program will print an error message and exit the loop using the `break` statement. Otherwise, the program will print the number and continue looping until the user enters a negative number. Once the loop has ended, the program will print a message indicating that it has finished.
阅读全文
相关推荐


















