c ++输入double,直到按下Enter键

时间:2015-06-01 03:56:46

标签: c++ double

我将此代码添加到用户输入的双打,并在用户输入负数时停止。我想更改它,以便当用户按下ENTER键并且不输入数字时它会停止,这可能吗?如果是这样,怎么样?

double sum = 0, n;

cout << endl;

do
{
    cout << "Enter an amount <negative to quit>: ";
    cin >> n;

    if(n >= 0)
    {
        sum += n;
    }
}while(n >= 0);

return sum;

2 个答案:

答案 0 :(得分:2)

使用getline(),如下所示:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s;
    double sum=0.0;
    while (1)
    {
        cout<<"Enter Number:";
        getline(cin, s);
        if (s.empty())
        {
            cout <<"Sum is: " <<sum;
            return 0;
        }
        else
        {
          sum=sum+ stod( s );
        }
    }    
    return 0;
}

示例输出:

  Enter Number:89
  Enter Number:89.9
  Enter Number:
  Sum is: 178.9 

答案 1 :(得分:1)

我通常从不做&gt; =因为这可能会变得混乱,特别是当你需要找到中位数或模式时。对于上面的代码,我就是这样做的。

  double sum =0;
  double n =0;

  while(cin >> n) // this will keep going as long as you either enter a letter or just enter
  {
      sum += n; // this will take any input that is good 

      if(!cin.good()) // this will break if anything but numbers are entered as long as you enter anything other then enter or a number
        break;

  }