Files

Reading numbers from CIN

The program below inputs numbers (from the user, or cin) and prints the total when the user enters 0 or a negative number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Read in numbers until 0 is entered, print total
#include<iostream>
using namespace std;
int main(void) {
 double num, total=0;
 cout<<"Enter a number:";
 cin>>num;
 while (num>0) {
  total+=num;
  cout<<"Enter a number:";
  cin>>num;
 } //while
 cout<<"Total="<<total<<"\n";
 system("pause");
 return 0;
} //main 
CODE
output

Please note the following:

  • Line 7: the first value is read before the loop.
  • Line 11: Each number after the first is read at the end of the loop. This make it easy to save the first number as largest and smallest.
  • Note that after either cin statement, the next statement is line 8 to verify that it is not zero.

NEXT: Read a list of numbers from file