1

The basic idea behind this was to do like this...

std::istringstream in{"",ios::ate};
while(in.empty()){
    //copy contents of 'cin' stream into the 'in'
}

I read a bit about streams, in Bjarne's book (mainly on how to use them), and also read some answers on stackoverflow, about copying contents of streams, and from an istream object to a istringstream object, but they didn't actually had any effect, and one more problem was that if i used getline(), it would wait for input, even if the delimiter is set to ' ', while i didn't wanted it to wait. *I tried running a for loop, and checking if the keyboard hits during that time, get into cin, and they did, but then still getline(cin, str, ' ') wait. With the main question in title, why does getline(cin,str,' ') wait, even though cin has spaces?

AdityaG15
  • 290
  • 3
  • 12
  • 1
    Hi. This is something most beginners run into. Unfortunately, it has nothing to do with C++, and more to do with the way the OS and run-time library feed the characters you type to `std::cin`. Usually, you have to type a newline before your program gets anything. Depending on OS and library, there may be settings you can tweak to change this. – Spencer Dec 26 '19 at 17:42
  • Also, your code contains a bug: As soon as `in` contains a single character it is no longer `empty`, and the loop will only execute once. – Spencer Dec 26 '19 at 17:45
  • @Spencer That was the idea, ie. to see if any key is pressed or not, so that as soon as in contains anything, it will get us out of loop. – AdityaG15 Dec 27 '19 at 07:11
  • `in` is a `stringstream` you declared. It has no connection to the keyboard, so `in.empty()` is never going to be change no matter what keys you press. – Spencer Dec 27 '19 at 12:02

1 Answers1

1

The interaction of the “console” with C++ are mostly system specific and don’t have any abstraction in C++. When typing something on a terminal screen the OS normally deals with line editing and passes the current line to the program only upon a newline being entered.

There are typically system specific approaches to disable the OS level interaction with the terminal. On POSIX systems the typical approach is to use tcgetattr() and tcsetattr() to enable cononical mode, i.e., setting the ICANON flag on the standard input stream (see, e.g., my answer to a similar question).

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Is there a way to extract from the cin stream, in some way, without the user pressing enter? Also even if i think of using enter to get of the loop, it will just wait at the getline() statement, for a newline, and not execute the loop. Is there a way to it? – AdityaG15 Dec 27 '19 at 07:13