How to Flush the Input Stream

flushing input stream: java

InputStream cannot be flushed. Why do you want to do this?
OutputStream can be flushed as it implements the interface Flushable. Flushing makes IMHO only sense in scenarios where data is written (to force a write of buffered data). Please see the documentation of Flushable for all implementing classes.

Is this the proper way to flush the C input stream?

All I hear is mixed arguments about how fflush() is undefined for the input stream

That's correct. Don't use fflush() to flush an input stream.

(A) will work for simple cases where you leave single character in the input stream (such as scanf() leaving a newline).

(B) Don't use. It's defined on some platforms. But don't rely on what standard calls undefined behaviour.

(C) Clearly the best out of the 3 options as it can "flush" any number of characters in the input stream.

But if you read lines (such as using fgets()), you'll probably have much less need to clear input streams.

How to empty an inputstream?

This is a tricky problem. And the core trickiness is that you don't know how much gibberish "COMMAND 1" is going to produce.

You could do something like this:

// send command 1
// while (is.available() > 0) {
// is.read()
// }

but that may not be reliable. The problem is that if the device produces the gibberish slowly or in a bursty fashion, is.available() call could return zero before the device has finished outputting the gibberish.

So a better approach may be to either wait for a short period before starting the read loop, or put a timer of some kind on the loop ... so that you keep trying for a period after the last time that available() returns a non-zero value.

Clearly, you will need to experiment to figure out which approach works best.


The other alternative (better IMO) is to figure out what the gibberish means ... at least to the degree that you can tell definitively when it has stopped.

How to flush the input stream?

It would help to know what operating system you're using, as this is a very operating-system-specific question. For example, Kylar's answer doesn't work on Windows because sys.stdin doesn't have a fileno attribute.

I was curious and threw together a solution using curses, but this won't work on Windows either:

#!/usr/bin/python                                                               

import time
import sys
import curses

def alarmloop(stdscr):
stdscr.addstr("How many seconds (alarm1)? ")
curses.echo()
alarm1 = int(stdscr.getstr())
while (1):
time.sleep(alarm1)
curses.flushinp()
stdscr.clear()
stdscr.addstr("Alarm1\n")
stdscr.addstr("Continue (Y/N)?[Y]:")
doit = stdscr.getch()
stdscr.addstr("\n")
stdscr.addstr("Input "+chr(doit)+"\n")
stdscr.refresh()
if doit == ord('N') or doit == ord('n'):
stdscr.addstr("Exiting.....\n")
break

curses.wrapper(alarmloop)

EDIT: ah, Windows. Then you can use the msvcrt module. Note that the code below isn't perfect, and it doesn't work in IDLE at all:

#!/usr/bin/python

import time
import subprocess
import sys
import msvcrt

alarm1 = int(raw_input("How many seconds (alarm1)? "))

while (1):
time.sleep(alarm1)
print "Alarm1"
sys.stdout.flush()

# Try to flush the buffer
while msvcrt.kbhit():
msvcrt.getch()

print "Continue (Y/N)?[Y]"
doit = msvcrt.getch()
print "Input",doit
if doit == 'N' or doit=='n':
print "Exiting....."
break

What does it mean to flush the input buffer?

"Flushing the input buffer" refers to the attempt to discard unwanted characters from the input stream so that they do not perturb later input calls.

In your code, it doesn't look like you'll have this problem, so flushing the input buffer should not be an issue for you.

The unwanted input issue typically occurs when you're doing input using scanf. scanf typically leaves the user's newline on the input buffer, but later calls to getchar or fgets (or even scanf) can be badly confused by this.

The problem with flushing the input is that there isn't really a good way of doing it. A popular although not recommended technique is to call fflush(stdin). That looks like it ought to be just the ticket, but the problem is that it's not well-defined and not guaranteed to work (although some programmers have found that it works well enough for them, on some platforms).

See this question and this question (maybe also this one) for much more on this issue.

java serialization socket inputstream flush

You shouldn't be reusing the same static socket reference server in each thread.

You want to use the new socket created upon each accept:

Socket newSocket = server.accept();

and pass that to each thread:

Thread t3 = new Thread (new TCPserver(3, newSocket));

Inside of TCPserver then, use ONLY the reference to newSocket.

To force you to do this, get rid of this declaration:

 static Socket server = null;  

and just make it a local variable in your main method:

 Socket server = new ServerSocket(5000);

Here is a server from one of my programs:

private ExecutorService executorService = Executors.newFixedThreadPool(10);

private void acceptConnections() {
listening = true;
while (listening) {
try {
final Socket connection = serverSocket.accept();
System.err.println("SERVER - connection from: " + connection.getInetAddress());
executorService.execute(new ConnectionHandler(connection));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

It uses a thread pool, instead of creating a new thead each time, but the basic idea is the same. My "ConnectionHandler" class is equivalent to your "TCPserver" class.

How do I flush the cin buffer?

Possibly:

std::cin.ignore(INT_MAX);

This would read in and ignore everything until EOF. (you can also supply a second argument which is the character to read until (ex: '\n' to ignore a single line).

Also: You probably want to do a: std::cin.clear(); before this too to reset the stream state.

How to clear input buffer in C?

The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.

The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.

If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.

As for the proposed solutions, see (again from the comp.lang.c FAQ):

  • How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work?
  • If fflush won't work, what can I use to flush input?

which basically state that the only portable approach is to do:

int c;
while ((c = getchar()) != '\n' && c != EOF) { }

Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.

Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?

Proper way to flush cin input

Answered by mikedu95 in a comment:

Read a whole line with getline, then perform string to integer conversion using stoi

#include <string>
#include <iostream>
using namespace std;

string str;
int a, b, c, d;

void main()
{
cout << "Reading a" << endl;
getline(cin, str);
a = stoi(str);

cout << "Reading b" << endl;
getline(cin, str);
b = stoi(str);

cout << "Reading c" << endl;
getline(cin, str);
c = stoi(str);

cout << a << " " << b << " " << c << endl;
system("pause");
}


Related Topics



Leave a reply



Submit