0

I'm an absolute beginner working through Stroustrup's 'Programming Principles and Practice' book.

In chapter 4 it introduced the End Of File input; Ctrl-D that worked on previous code snippets. The code I'm now working on is this simple vector example.

I believe Ctrl-D should exit the range-for loop and then cout the calculations, however this isn't working. I can only exit the program, and see no results, via Ctrl-Z (stopped), Ctrl-C or the | (pipe) symbol, anything else just continues the input loop.

I am on linux using a terminal emulator (terminator) to write, run and compile. I have tried the same code in Code::Blocks and the output is exactly the same.

Please; how can I break out of the input loop?

#include "std_lib_facilities.h"      //provided PPP header file

int main()
{
    vector<double>temps;
    for (double temp; cin >> temp;)  //get stuck in here
        temps.push_back(temp);

    double sum=0;                    //want to get to here 
    for (double x : temps) sum += x;
    cout << "Average temperature: " << sum/temps.size() << endl;

    sort(temps.begin(),temps.end());
    cout << "Median temperature: " << temps[temps.size()/2] << endl;
}

2 Answers2

0

On Unix-like systems (at least by default), an end-of-file condition is triggered by typing Ctrl-D at the beginning of a line or by typing Ctrl-D twice if you're not at the beginning of a line. From this question's accepted answer: Why do I need to type Ctrl-D twice to mark end-of-file?

Community
  • 1
  • 1
loafbit
  • 33
  • 6
  • Ctrl-D twice (and more) doesn't do anything. – Cdr.Jameson Apr 22 '16 at 08:53
  • Thanks for the link, I still can't get it to break out but the article did lead me to test my EOF input using a while loop. Which works...Ctrl-D did break out of the while loop. I'm wondering why it is not breaking out of the for loop. – Cdr.Jameson Apr 22 '16 at 09:05
  • @Cdr.Jameson on my terminal, your program works.I can't see any difference between while and for loop. – loafbit Apr 22 '16 at 09:17
  • Thanks for trying it out. I have no idea why Ctrl-D works for a while loop and not a for loop..I rewrote Bjarne's code (sacrilege I know!) to use a for loop and it still doesn't work. – Cdr.Jameson Apr 22 '16 at 09:20
0

you dont seem to get out of for loop. either you can define the ampunt of values you are taking so it loops that many times, or you say while(input!=X) so that when you give an X value it leaves the loop. And check that for should be used with 3 statements not 2. Good luck

B. Koksal
  • 1
  • 2