c++双击输入,直到按下Enter键

c++ input double until Enter key is pressed

本文关键字:Enter 双击 输入 c++      更新时间:2023-10-16

我有这段代码,它将用户输入的双精度加起来,并在用户输入负数时停止。我想改变它,这样当用户按下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;

使用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 

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

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