Here are some things that may help you improve your program.
Avoid hardcoding filenames
This program would be a bit more usable if it either read from std::cin
or was passed a filename as a parameter. Right now, it's quite inflexible because the input filename is hardcoded.
Fix the bug
Unless it's specifically disallowed to have the number 0
in the input stream, this line is a bug and should simply be deleted:
if (!n) break;
Initialize variables when they're declared
In C++, it's usually advantageous to initialize variables when they're declared. This allows us to always count on some kind of rational value for it, regardless of what happens in the rest of the program.
Don't use system("PAUSE")
There are two reasons not to use system("cls")
or system("PAUSE")
. The first is that it is not portable to other operating systems which you may or may not care about now. The second is that it's a security hole, which you absolutely must care about. Specifically, if some program is defined and named cls
or Color
, your program will execute that program instead of what you intend, and that other program could be anything. First, isolate these into a seperate functions cls()
and color()
and then modify your code to call those functions instead of system
. Then rewrite the contents of those functions to do what you want using C++. For example:
void pause() {
getchar();
}
Omit the return
statement in main
Generally, (although not guaranteed by the standard), a nonzero return value is understood by the operating system to mean that an error has occured, while in this case, the code always returns a non-zero value. Better would be to simply delete the return
. When a C or C++ program reaches the end of main
the compiler will automatically generate code to return 0, so there is no need to put return 0;
explicitly at the end of main
.
Use standard algorithms
There are std::min
and std::max
which could be used for this program.
Putting it all together
Here's one way to rewrite the code so that it uses all of the suggestions above:
#include <iostream>
#include <limits>
#include <algorithm>
int main() {
unsigned n{0};
int min{std::numeric_limits<int>::max()};
int max{std::numeric_limits<int>::min()};
int number;
while (std::cin >> number) {
++n;
min = std::min(min, number);
max = std::max(max, number);
}
std::cout << "numbers: " << n << "\n";
if (n) {
std::cout << "minimum: " << min
<< "\nmaximum: " << max
<< '\n';
}
}