c++getstdcin

trying to understand std::cin.get()


Hi all so i was reading about std::cin.get() func and read that we use it to capture the newline char that was entered after entering any input to the console. But i kind of got confused while writing a small very basic program and couldn't understand its behavior.

so my program is for the exercise in c++ primer plus. Anyways the code is below:

#include <iostream>
#include <cstring>

void countWords () {
  char word [100];
  char wordDone [] = "done";
  int count = 0;

  std::cout << "Enter words (to stop, type the word done): \n";
  std::cin >> word;

  while (strcmp(word, wordDone) != 0) {
    std::cin >> word;
    count += 1;
  }

  std::cout << "You entered a total of " << count << " words.";

  std::cin.get();
  std::cin.get();  
}

int main () {
  countWords ();

  std::cin.get();
  return 0;
}

Now here the issue is when i run the above code, the screen gives me proper output but it disappears without waiting for me to enter a return.

But when instead of creating the above countWords() func, if i write the whole code in the main() func, it works perfectly, which is what is confusing me a lot.

As per my understanding, when i enter the char array in console and press return, the buffer keeps the console data and the newline in queue, and after the while loop is processed and the cout is displayed, the return is absorbed by the first std::cin.get(). So then the program should wait for me to enter another return which will then be abosorbed by second cin.get() and also it should ask me another return since there is a cin.get() in main function as well. But for some reason which i am not able to figure out, the output screen just disappears.

Any comments or explanation please??


Solution

  • It would seem you have something stuck in the buffer which is causing all of your gets to be filled.

    I would suggest the following:

    cin.ignore(-1, '\n');