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

Tyro[17] nospam at home.com
Mon Mar 26 14:12:27 PDT 2012


On Monday, 26 March 2012 at 17:34:37 UTC, Ali Çehreli wrote:
> On 03/26/2012 04:55 AM, Tyro[17] wrote:
>
> >> > readf(" %s", &s2); // No matter how many read attempts
>
> That's the actual problem, and ironically is already known to 
> you. :) Use a \n at the end of that format string.

Thanks. I'le use chomp(readln()) in the future.

> >>
> >> I advise reading string by readln(). You can call chomp() to
> get rid
> >> of whitespace around it:
> >>
> >> while (s2.length == 0) {
> >> s2 = chomp(readln());
> >> }
> >
> > You can achieve the same with:
> >
> > readf(" %s\n", &s2);
>
> Thank you. However, that method does not remove trailing 
> whitespace.
>
> > My goal however, is not to read one line of information.
> Rather, it is to
> > read multiple lines of information from standard input. I get
> close to
> > being able to do so if i don't including "\n" as a part of my
> format string
> > or if I changing your suggestion to
> >
> > while (!stdin.eol()) {
> > s2 = chomp(readln());
> > }
> >
> > but again I run into the predicament was before, a need to
> close the
> > the stream with Ctrl-D/Ctrl-Z.
>
> If I understand you correctly, the following program works for 
> me:
>
> import std.stdio;
> import std.string;
>
> void main(string[] args)
> {
>     string s1;
>     double d;
>     string s2;

Actually the problem is right here:

>     writeln("Enter a @ terminated string (multiline ok):");
>     readf(" %s@", &s1);
>     auto arr = s1.split();

I don't want to provide an explicit terminator, but instead
rely on Ctrl-D/Ctrl-Z to do the job while being able to
continue processing read request. As explained by Andrei,
this is not possible. But in my mind if the stdin stream
can be opened once, it can be opened again. What is the
negative effect of testing if it is closed and reopening it
on entering readf? Especially since there is a unique
implementation of readf to deal with input from stdin.

What is wrong with implementing reopen() in File for
specific use with stdin and then implementing readf
like this:

uint readf(A...)(in char[] format, A args)
{
     if(stdin.eof) stdin.reopen();
     return stdin.readf(format, args);
}

Andrew


More information about the Digitalmars-d mailing list