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

Tyro[17] nospam at home.com
Mon Mar 26 05:29:24 PDT 2012


First of all thank your very much for your assistance.

On Sunday, 25 March 2012 at 15:04:30 UTC, Ali Çehreli wrote:
> On 03/25/2012 06:00 AM, Tyro[17] wrote:
> > I am trying to figure out the cause of my problem in the
> following post:
> >
> > 
> http://forum.dlang.org/thread/qfbugjkrerfboqhvjttw@forum.dlang.org
>
> Sorry that I missed your question there. :(
>
> > and encountered something peculiar about reading strings.
> Whenever a
> > distinct terminator is indicated in the input format (ex. "
> %s@", @
> > being the terminator), readf() leaves the terminator on the
> input buffer
> > after reading the data. If no terminator is specified the
> only way to
> > indicate end of input is to use ctrl-d (ctrl-z on windows),
> however that
> > causes the eof indicator to be set to true and the stream is
> marked as
> > empty for all future attempts to access stdin.
> >
> > void main(string[] args)
> > {
> > string s1;
> > double d;
> > string s2;
> >
> > writeln("Enter a @ terminated string (multiline ok):");
> > readf(" %s@", &s1);
> > auto arr = s1.split();
> >
> > if (!stdin.eof()) {
> > writeln("The stream is not empty.");
> > } else {
> > writeln("The stream is empty.");
> > }
> > writeln("Enter another string (terminated with
> cntrl-d|ctrl-z):");
>
> I am not sure about the cntrl-d|ctrl-z part though. Since it 
> terminates the input, the program should not be able to read 
> any more characters.
>
> > readf(" %s", &s2); // No matter how many read attempts
>
> 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);

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.

Andrew





More information about the Digitalmars-d mailing list