I just started learning c++ and is learning topics related to cin, cin.get. In one of my assignments, the requirement is this:
Write a program that reads in a list of integer numbers and prints the largest and the smallest number.
You can assume that the the user's input is always valid.
You can assume that the numbers in the list are separated by one space character and that the character following the last number in the list is the newline character .
Implement a loop in which the above actions are repeated until the user requests to quit.
The code I came up with is:
using namespace std;
int main()
{
char ch = ' ';
int max=0;
do
{
int x;
cin >> x;
ch = cin.get();
if (max = 0) { max = x; };
if (x > max) { max = x; };
} while (ch != '\n');
cout << "maximum=" << max << endl;
return 0;
}
I was expecting to have this return the maximum of the numbers in the list. But it turned out only to return the last integer in the list.
I also don't quite get why the line:
cin >> x;
ch = cin.get();
makes the program able to accept a list of numbers. Isn't cin suppose to ask the user to input some stuff, as well as cin.get? In another word, shouldn't the user encounter input two times? But why is it when I run I am only asked to input once?
After some adjustment using the comments in this post, I was able to come up with the code as such:
int main()
{
cout << "Enter the list of integer numbers: ";
char ch = ' ';
int max=0;
int min = 0;
do
{
int x;
cin >> x;
ch = cin.get();
if (max == 0) { max = x; };
if (x > max) { max = x; };
if (min == 0) { min = x; };
if (x < min) { min = x; };
} while (ch != '\n');
cout << "maximum=" << max << endl;
cout << "minimum=" << min << endl;
return 0;
My final question is: How can I satisfy the requirement of this assignment "Implement a loop in which the above actions are repeated until the user requests to quit."