stdio line-streaming revisited

Roberto Mariottini rmariottini at mail.com
Fri Mar 30 00:54:20 PDT 2007


Derek Parnell wrote:
[...]
> This would mean that the sequence example given by Kris ...
> 
>     Cout ("Please enter your name: ").flush;
>     Cout ("Hello, ") (Cin.get);
> 
> gets transformed in to 
> 
>     flush( opCall( Cout, "Please enter your name: "));
>     opCall( opCall( Cout, "Hello, "), get(Cin));
> 
> The first statement will end up displaying the text on the console, leaving
> the cursor to the right of the ':' character. Now if the 'get' is called
> next, the user types in her name, say "mavis" and the screen will show ...
> 
>   Please enter your name: mavis
>   _
> 
> and then the inner 'opCall' is run which will show (assuming a flush) ...
> 
>   Please enter your name: mavis
>   Hello, mavis
>   _

Right, but you are assuming a flush() call that is missing (see below).

> 
> However, if the inner 'opCall' is called first the screen will show ...
> 
>   Please enter your name: Hello, _
>
> and the user types in her name and we get ...
> 
>   Please enter your name: Hello, mavis
>   mavis
>   _

No, you are again assuming a flush() call. As Kris explained, the 
example works only because of buffering: no flush() is called, so the 
"Hello, " string stays in the output buffer until the Cin.get() call 
flushes it.

The example works with every order of evaluation, if and only if the 
output buffer length is equal or greater than the length of the string 
"Hello, ".

> So the order is reasonable important to sort out.
> 
> Being the conservative procedural type of coder, I would have probably have
> coded ...
> 
>     char[] userName;
>     Cout ("Please enter your name: ").flush;

This flush() call is unneeded.

>     userName = Cin.get();
>     Cout ("Hello, ");
>     Cout (userName);
>     Cout.flush;
 >
> Actually, now that I think about it, I'd really do ...
> 
>     char[] userName;
>     char[] myResponse;
> 
>     Cout ("Please enter your name: ");
>     Cout.flush;
>     userName = Cin.get();
>     myResponse = std.string.format("Hello, %s\n", userName);
>     Cout.( myResponse );
>     Cout.flush;
> 
> That is of course, if I'd really used stdin/stdout in that manner at all
> <G>

<G>

Ciao



More information about the Digitalmars-d mailing list