[英]c++ How do i end a while loop that add numbers without using a number as a trigger to end the loop
I'm trying to write a program that adds numbers continuously until the user enters a word or something to stop the program. 我正在尝试编写一个程序,该程序可以连续加数字,直到用户输入单词或其他东西停止程序为止。 Currently, I used -9999 but what if the user want to add -9999? 目前,我使用-9999,但是如果用户要添加-9999怎么办? I'm new at this can someone help please. 我是新手,请有人帮忙。
float Addition()
{
Sum = 0;
cout << "Please enter number you wish to add:" << endl;
cin >> num;
while(num != -9999)
{
Sum += num;
cout << "Sum is:" << Sum << endl;
cout << "Please enter number or enter -9999 to exit" << endl;
cin >> num;
if(!cin.good())
{
throw exception();
}
}
}
The usual approach is to change the loop to: 通常的方法是将循环更改为:
while (cin >> num)
This will continue to prompt for input until ean nd of file condition which, depending on your operating system, is signaled by typing either Ctrl-D or Ctrl-Z . 这将继续提示输入,直到显示文件状态为止,具体取决于您的操作系统,通过键入Ctrl-D或Ctrl-Z发出信号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.