c++ input double until Enter key is pressed -
i have code adds doubles entered user , stops when user enters negative number. want change stop when user presses enter key , doesn't enter number, possible? , if so, how?
double sum = 0, n; cout << endl; { cout << "enter amount <negative quit>: "; cin >> n; if(n >= 0) { sum += n; } }while(n >= 0); return sum;
use getline()
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
Comments
Post a Comment