Reading a line from stdin

Ali Çehreli acehreli at yahoo.com
Wed Mar 16 06:54:57 PDT 2011


On 03/16/2011 05:49 AM, Kagamin wrote:
> Ali ǥhreli Wrote:
>
>> The following program may be surprising to the novice:
>>
>> import std.stdio;
>>
>> void main()
>> {
>>       write("What is your name? ");
>>       string name = readln();
>>       writeln("Hi ", name, "!");
>> }
>
> What if the user typed leading spaces? Will the program operate as you expect?

I would not like the leading spaces either, and that's another issue: 
contrary to readln(), readf() leaves the newline character in the input. 
I was about to start adopting the guideline of using " %s" (note the 
space) when reading formatted unless there is a reason not to. Most of 
the time the newline left from the previous input has nothing to do with 
the next read.

Otherwise the following program gets stuck:

import std.stdio;

void main()
{
     int i, j;
     readf("%s%s", &i, &j);
}

As a result, my current guideline is "put a space before every format 
specifier":

     readf(" %s %s", &i, &j);

This is a departure from C's scanf but is more consistent.

I don't want to accept and teach buggy behavior and that's why I asked 
on the D forum. Unfortunately I failed to attract interest there.

After accepting the above, I wanted to readf() lines too:

import std.stdio;

void main()
{
     string s;
     readf(" %s", &s);
     writeln(s);
}

As another departure from C, readf() does not stop at the first 
whitespace. It reads until the end of the input. Ok, I like that 
behavior but it's not useful for "What is your name? " like inputs.

So it led me to readln().

I don't have a problem with whitespace being left in the line, I just 
want to know whether that's the intended or accepted behavior.

Ali


More information about the Digitalmars-d-learn mailing list