【问题标题】:c++ How do i end a while loop that add numbers without using a number as a trigger to end the loopc ++我如何结束添加数字而不使用数字作为触发器来结束循环的while循环
【发布时间】:2016-12-08 01:30:50
【问题描述】:

我正在尝试编写一个程序,该程序可以连续添加数字,直到用户输入单词或其他内容来停止程序。目前,我使用的是 -9999,但如果用户想添加 -9999 怎么办?我是这方面的新手,请有人帮忙。

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();
        }                   
    }
}

【问题讨论】:

  • 将输入改为字符串,然后将其转换为数字。如果用户输入的内容无法解析为数字,请停止循环(只是一个想法)。

标签: c++ while-loop type-conversion


【解决方案1】:

通常的做法是将循环改为:

while (cin >> num)

这将继续提示输入,直到找到文件条件为止,根据您的操作系统,通过键入 Ctrl-DCtrl-Z 发出信号.

【讨论】:

  • 是不是 Control-D 而不是 Control-C?
  • 是的,它是......更正了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 1970-01-01
  • 2022-01-19
  • 2021-11-09
  • 2018-12-29
  • 1970-01-01
  • 2014-04-20
相关资源
最近更新 更多