How to Humanize Numerical Input|Output
Steven Schveighoffer
schveiguy at gmail.com
Mon Sep 9 20:36:05 UTC 2024
On Monday, 9 September 2024 at 20:02:48 UTC, Jabari Zakiya wrote:
> I have this code to input integer values:
>
> ```
> ulong[] x;
> foreach (_; 0 .. 2) { ulong a; readf!" %d"(a); x ~= a; }
> end_num = max(x[0], 3);
> start_num = max(x[1], 3);
> if (start_num > end_num) swap(start_num, end_num);
> start_num = start_num | 1; // if start_num even
> add 1
> end_num = (end_num - 1) | 1; // if end_num even
> subtract 1
> if (end_num - start_num < 2) { start_num = 7; end_num = 7; }
>
> ```
>
> Currently I have to enter data as: 123456 789102
>
> I'd like to enter data as: 123_456 789_10
>
> How do I do that?
>
> Also for output, I do this:
>
> ```
> writeln("total twins = ", twinscnt, "; last twin = ", last_twin
> - 1, "+/-1");
> ```
>
> I'd also like to output data as: 123,987 or 123_987
Given that you are just removing separators, just filter those
out from your inputs.
Just get the raw text as a string, and use `formattedRead` with
an appropriate filtering range to get what you want.
Something like
```d
import std.string;
import std.algorithm;
import std.format;
import std.stdio;
auto str = readln(); // get the line
auto filtered = str.filter!(c => "_,".indexOf(c) == -1); //
filter out separators
ulong[] x;
foreach(_; 0 .. 2) {ulong a; filtered.formattedRead(" %d", a); x
~= a; }
```
And I'd also recommend trying out range chaining:
```d
ulong[] x = str
.filter!(c => "_,".indexOf(c) == -1)
.splitter
.map!(s => s.to!ulong)
.array;
```
-Steve
More information about the Digitalmars-d-learn
mailing list