how stdin stream works?

Ali Çehreli acehreli at yahoo.com
Thu Aug 20 19:13:31 UTC 2020


On 8/19/20 11:46 AM, Flade wrote:

>> Try instead getting a line via readln, and then trying to read that 
>> into your expected input.
>>
>> -Steve
> 
> Thanks Steve! I will get the input a string then as you said and then 
> I'll try to convert it! Thanks a lot, have a nice day!

In some cases clearerr() and readln() may be what is needed:

import std.stdio;

void main() {
   int x;

   bool accepted = false;

   while (!accepted) {
     try {
       write("x: ");
       readf(" %d", x);
       accepted = true;

     } catch (Exception msg) {

       writeln("Please give a right coordinate");
       stdin.clearerr();
       stdin.readln();
     }
   }

   writeln("x is ", x);
}

Note that I used " %d" because "%d/n" would not clean when nothing was 
input by just hitting the Enter key. A space character in the format 
string means "read and ignore any whitespace at this point" and I like 
it. :)

Also note I changed the name of the variable as 'accepted'. :)

Ali


More information about the Digitalmars-d-learn mailing list