#include <iostream>
usingnamespace std;
int input(int);
int main()
{
int num, temp;
cout << "Input the number of temperatures (not more than 10): ";
cin >> num;
while ((num < 0) || (num > 10))
{
cout << "Invalid input."<<endl;
cout << "Input the number of temperatures (not more than 10): ";
cin >> num;
}
input(num);
return 0;
}
int input(int number)
{
int temperature[number];
for (int i = 0; i < number; i++)
{
cout << "Input Temperature: ";
cin >> temperature[i];
}
return temperature[number];
}
If you input 15 the program will say Invalid Output
Then asks you to input another number.
If you input 5 after that, it will ask you to input the temperature 10 times.
I input 15 then 5 and it asks me to input the temperature 5 times. I'm not saying you are wrong though, the behaviour you describe could be a result of undefined behaviour (see below).
What do you mean by illegal?
The size of an array has to be a compile time constant (except if you dynamically allocate the array) but some compilers allow it anyway. Your compiler clearly allows it so this is not the cause of your problem.
return temperature[number];
This is a bit of a problem though. This tries to access the element at index number.
Valid indices for the temperature array are 0 to number-1.
This means you are accessing out of bounds, which means the behaviour is undefined meaning anything could happen.
Firstly, if you run that program, it will immediately say that it has an invalid input, even though the user hasn't done anything. Secondly, while I know the OS usually cleans things like this up, you're not using delete[] on temp. Furthermore, this is a beginner's forums and you've just given an example program that not only doesn't delete heap allocated memory, but uses raw owning pointers, something that there is no need to teach people who are learning basic C++ now we have C++ 11 with vectors and smart pointers (and also you used using namespace std). Why do you keep posting manual memory management examples?
Oh come on, I just wanted to know why you do that (there might be a valid reason which I don't know), and to point out to supernoob about having to always use delete with new and delete[] with new[] so they don't end up with memory leak problems.
Setting num = -1 serves two purposes - first, to initialise num, and second and more importantly to ensure the while loop is entered. It's a common trick of the trade given the while( x<0 ... test.
Yep, it will output "invalid etc".
This leaves you, as the programmer, with all sorts of design problems to solve.
- leave the offending line out?
- adopt a more sophisticated error trapping routine?
- leave it as it is - sort of makes sense?