Reputation: 43
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? 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;
Upvotes: 2
Views: 1807
Reputation: 102
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;
}
Upvotes: 1
Reputation: 6126
Use getline()
as below:
#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
Upvotes: 2