reading formatted strings: readf("%s", &stringvar)

Tyro[17] nospam at home.com
Tue Mar 27 05:54:45 PDT 2012


On Tuesday, 27 March 2012 at 00:05:51 UTC, Andrei Alexandrescu 
wrote:
> On 3/26/12 2:52 PM, Tyro[17] wrote:
>> Couldn't the state of stdin be checked upon entrance into readf
>> and reopened if it is already closed?
>
> That won't work.

But this does:

import std.stdio, std.array;

extern(C) // As defined for MAC OS X Lion
{
     immutable TCSANOW = 0;
     immutable NCCS    = 20;
     immutable VEOF    = 0;	/* ICANON */

     int tcgetattr(int fd, termios *termios_p);
     int tcsetattr(int fd, int actions, termios *termios_p);

     alias ulong	tcflag_t;
     alias ubyte	cc_t;
     alias ulong	speed_t;

     struct termios {
         tcflag_t	c_iflag;	/* input flags */
         tcflag_t	c_oflag;	/* output flags */
         tcflag_t	c_cflag;	/* control flags */
         tcflag_t	c_lflag;	/* local flags */
         cc_t		c_cc[NCCS];	/* control chars */
         speed_t		c_ispeed;	/* input speed */
         speed_t		c_ospeed;	/* output speed */
     }
}

void main(string[] args)
{
     termios oldT;
     tcgetattr(0, &oldT);

     auto newT = oldT;
     newT.c_cc[VEOF]  = 3;  // temporary reassignment of EOF 
indicator.
     tcsetattr(0,TCSANOW,&newT);

     string s1;
     writeln("Enter Ctrl-D terminated string (multiline ok):");

     readf(" %s\x04", &s1);
     tcsetattr(0,TCSANOW,&oldT);

     auto arr = s1.split();
     writeln(arr);

     int data;
     readf(" %s", &data);
     writeln(i);
}

Could that technique be used to implement readf for stdin?

>> Wouldn't that accomplish the desired effect while avoiding
>> the pitfalls of scanf?
>
> I don't think this is a pitfall. Essentially you don't have a 
> definition of what constitutes a chunk of input. Once you get 
> that define, you should be able to express it more or less 
> easily.
>

I'm of the opinion that Ctrl-D defines the boundary of that
chunk of input. We simply have to prevent it from closing
the stream when working with stdin.

> Andrei



More information about the Digitalmars-d mailing list