Jul 16, 2014 at 6:43pm UTC
You have "cin>>temp" as your terminating condition.
This will keep pushing back the input "temp" to temps vector until your cin fails when, for example, you try to input a character/string instead of a number.
Last edited on Jul 16, 2014 at 6:44pm UTC
Jul 16, 2014 at 6:45pm UTC
The first example is a range-based for loop. The other two are normal for loops.
1 2 3 4
for (initialization(s); condition(s); increment(s))
{
stuff to execute
}
http://www.cplusplus.com/doc/tutorial/control/
So in other words the last example will execute until it cin is false (which will be when you type in something erroneously)
http://www.cplusplus.com/reference/ios/ios/operator_bool/
with that particular case I prefer a while loop.
Something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <vector>
#include <iostream>
int main()
{
std::vector<double > temps;
double temp = 0.0;
while (std::cout << "Please enter a number: " && std::cin >> temp)
{
temps.push_back(temp);
}
std::cout << "The numbers entered were: " ;
for (double const &element : temps )
{
std::cout << element << ' ' ;
}
return 0;
}
*added vector and iostream includes so it will properly run
Last edited on Jul 16, 2014 at 6:46pm UTC