hey guys, i cant figure out one thing ive tried if statements, do whiles, while loops and i cant get my getTemp function to exit out when user enters negative 1. any tips?
void getTemp(double temp[], int size)
{
for (int index = 0; index < size; index++)
{
if (index != -1)
{
cout << "enter temperature #(-1 to exit) " << (index+1) << ": ";
cin >> temp[index];
}
elsebreak;
}
}
You may want to take your input into a temporary variable and test it rather than going directly into temp[index]. otherwise you'll end up with the -1 value being inserted into the array.
i cant get my getTemp function to exit out when user enters negative 1
What you want is exit when the user enters a -1 temperature not index index will never be negative as you are incrementing it from 0
for (int index = 0; index < size; index++)
{
if (index != -1)
{
cout << "enter temperature #(-1 to exit) " << (index+1) << ": ";
cin >> temp[index];
}
}
/// you can use this
int index=0, value;
While (index <size)
{
cout << "enter temperature #(-1 to exit) " << (index+1) << ": ";
cin >> value;
if (value==-1)
exit (1);/// include cstdlib or use return
temp [i]=value; ++i;
}
both does equally the same thing btw there is also readability. Well if for loop are your best choice you can switch that code into a for loop they are just equal ,
1 2 3 4 5 6 7 8 9 10 11
int value;
for (int index=0; index <size; index++)
{
cout << "enter temperature #(-1 to exit) " << (index+1) << ": ";
cin >> value;
if (value==-1) exit (1);/// include cstdlib or use return
////edit: you dont want to use exit am sure use break as Essclercuffi suggested
temp [i]=value;
}
The main difference between the for's and the while's is a matter of pragmatics: we usually use for when there is a known number of iterations, and use while constructs when the number of iterations in not known in advance.