cin question

How come this function halts my program when i enter "2000 4"
1
2
3
4
5
6
7
/* clear input buffer */
void cib()
{
  char ch;
  while(ch != '\n')
    cin >> ch;
}
More info please:
  ① how is the function used?
  ② how do you detect the error?
Also is there a way to do this without reading input if there is no data in the buffer.
1
2
3
4
5
void cib() {
  char ch = 0;
  while(ch != '\n')
    ch = getchar();
}
it's used after I cin>>integer to remove the rest of the buffer so the next cin read will be acurate. I want to basically receive input from the buffer and disregard the remaining buffer if they say enter "2000 4" instead of entering "2000" for date. the second cib function there works but what if there was no data from the buffer then it halts program until it reads something.
if there was no data from the buffer then it halts program until it reads something.


Correct. C/C++ as standard doesn't have a non-blocking input function.

If you're using Windows, there is _kbhit() defined in conio.h which returns true if input is waiting or false if not. However, this is a throw-back to the days of ms-dos and is NOT portable.

Normal c/c++ input doesn't return until a new-line has been encountered (or eof etc) - then the input is available to be processed.

Again in c/c++ there's no standard way of obtaining a char as the keyboard key is pressed. In conio.h there is _getch() (non-echo) and _getche() (echo) which will get one char if available from the keyboard without waiting for the '\n' to be entered. But again this is NOT portable.

Again for Windows there are the console input/output API's with which you can do just about anything you want - but this is Windows only, and is not portable.

If you have input of "2000 04\n" then you can just obtain 2000 and discard the 04 (just do a stream extraction and then .ignore() but this means that at some point a new-line is entered and the extraction etc only occurs when this happens.
Topic archived. No new replies allowed.