How to use "read_bool"?
simendsjo
simendsjo at gmail.com
Fri Aug 3 09:12:41 PDT 2012
On Fri, 03 Aug 2012 08:05:46 +0200, Ali Çehreli <acehreli at yahoo.com> wrote:
> On 08/02/2012 09:17 PM, Zeh wrote:
> > Hi, i am just a newbie trying learn D. But, i get having some trouble
> > with "read_bool". More specifically on program of this lesson:
>
> As Timon said, read_bool() is a separate function on the same page, a
> little after main():
>
> bool read_bool(string message)
> {
> // Print the message
> writef(message ~ "(false or true) ");
>
> // Read the line as a string
> string input;
> while (input.length == 0) {
> input = chomp(readln());
> }
>
> // Produce a 'bool' value from that string
> bool result = to!bool(input);
>
> // Return the result to the caller
> return result;
> }
>
> Unlike Timon's function, you must enter either "false" or "true" with
> the one above.
>
> Ali
>
What tutorials is this? Here's another version:
import std.stdio, std.string, std.conv;
bool read_bool(in string message) { // in as we don't escape or modify the
input
while(true) { // loop until we get true/false
write(message, " (false or true): "); // avoid concat allocation
string input;
do { // no need to check input on entering
input = readln().chomp(); // UFCS
} while(!input); // no need to check length
try
return input.to!bool;
catch {} // don't care if it's not true/false. Keep nagging
}
}
void main() {
auto input = read_bool("Do it?");
writeln(input ? "Hell yeah, do it!" : "No way!");
}
More information about the Digitalmars-d-learn
mailing list