简体   繁体   English

c + +输入两次直到按Enter键

[英]c++ input double until Enter key is pressed

I have this code that adds up doubles entered by the user and stops when the user enters a negative number. 我有这段代码,将用户输入的双精度加起来,并在用户输入负数时停止。 I want to change it so that it will stop when the user presses the ENTER key and doesn't enter a number, is this possible? 我想对其进行更改,以使其在用户按下ENTER键并且不输入数字时停止,这可能吗? And if so, how? 如果是这样,怎么办?

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;

Use getline() as below: 使用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;
}

An example output: 输出示例:

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

I usually never do >= because this can get messy especially when you need to find the median or mode. 我通常从不做> =,因为这会变得凌乱,尤其是当您需要找到中位数或众数时。 For the code above this is how I would go about doing it. 对于上面的代码,这就是我要做的事情。

  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;

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM