Problem with using readln.

Ivan Kazmenko via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Apr 30 04:16:10 PDT 2017


On Sunday, 30 April 2017 at 02:07:48 UTC, JV wrote:
> Hello i'm kinda new to D language and i wanted to make a simple 
> program
> but somehow my input does no go to my if statements and just 
> continues to ask for the user to input.Kindly help me

One way would be:

     import std.stdio;
     int x;
     readf (" %s", &x);

The "%s" means "default format for the type", which is I believe 
"%d" (decimal) for the int type.  The space before "%s" is to 
skip all whitespace before the actual input, it will matter when 
you read your second integer:

     readf ("%s%s", &x, &y); // error, got space for y instead of 
a digit
     readf ("%s %s", &x, &y); // ok

Another way is:

     import std.conv, std.stdio, std.string;
     int x = readln.strip.to!int;

Here, we read the line with readln, strip the trailing whitespace 
with strip, and convert the resulting string to an int with 
to!int.

Also, you might want to look at the corresponding chapter in Ali 
Cehreli's book:
http://ddili.org/ders/d.en/input.html

Ivan Kazmenko.



More information about the Digitalmars-d-learn mailing list