0

I'm going through B. Stroustrup's Programming Principles and Practice Using C++ and I encountered a problem doing one of the exercises. I'm using Windows 10 (I believe, that's relevant here). The code below is supposed to ask the user for words, which are to be printed back. However, if a word is "broccoli", then instead of "broccoli", "BLEEP" will be printed.

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }

int main()
{
    string bad_word = "broccoli";
    cout << "type in some words\n";
    vector <string> words;
    for (string temp; cin >> temp; )
        words.push_back(temp);
    cout << "There are " << words.size() << " words in vector 'words'.\n";

    for (string word : words) {
        if (word != bad_word)
            cout << word;
        else
            cout << "BLEEP";
    }

    keep_window_open();
    return 0;
}

So, I have my program ask me for words, I print some, then hit Ctrl+Z + Enter, and nothing happens. If I do that again, the console closes. Why doesn't it print the number of words as specified by this line?

cout << "There are " << words.size() << " words in vector 'words'.\n";

Why does the program finish execution after I hit Ctrl+Z+Enter the second time? I want to understand what the problem really is here. Thank you.

  • 1
    It could be because you are using Visual Studio which behaves a bit weird. Try starting your program with CTRL+F5 instead of just F5 and see if that helps. – nwp Jan 22 '18 at 12:48
  • CTRL+Z sends to background on linux. https://superuser.com/a/476875/459974 (to add some info) you are on windows 10, then it´s not the problem – Alejandro Teixeira Muñoz Jan 22 '18 at 12:50
  • Your `keep_window_open` isn't going to work; `cin` is already in a "bad" (like eof) state after your first loop, so reading from it again is invalid. (Generally, you should start console applications from a terminal, don't know what the "new" one in windows is called but it should open if you run powershell) – Cubic Jan 22 '18 at 12:50
  • On Linux, Cntrl+D works fine. – Abdallah Jan 22 '18 at 12:52
  • 1
    Maybe you should add a `cout << endl;` after the loop, otherwise your output buffer might not be flushed – grek40 Jan 22 '18 at 12:52

1 Answers1

0

ctrl-z is an end of file signal. This disables reading from the input stream (cin).

So your keep window open function returns immediately without waiting(because reading is not possible), and your console closes.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31