How else can I write for(double temp; cin>>temp;)?

I'm very new to programming and having a hard time understanding how the loop condition works when prompting the user for input.

For example you can write

1
2
vector<int> v;
for (int x : v)


or

 
for(int i = 0; i < v.size(); i++;)


But what about this case:

1
2
3
4
5
6
int main()
{
          vector<double> temps; 
          for (double temp; cin>>temp; ) 
                    temps.push_back(temp);     
}
That's a lousy use case for a for loop.

1
2
3
4
5
    vector<double> temps;
    double temp ;

    while (cin >> temp)
        temps.push_back(temp);


or if you're looking for a way to take the extraction out of the loop condition, the following is equivalent:

1
2
3
4
5
6
7
8
9
    vector<double> temps;
    double temp ;

    cin >> temp;
    while (cin)
    {
        temps.push_back(temp);
        cin >> temp;
    }
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
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
Topic archived. No new replies allowed.