【问题标题】:Does D have anything like Java's Scanner?D 有类似 Java 的 Scanner 的东西吗?
【发布时间】:2014-03-17 19:49:00
【问题描述】:

在 D 中是否有类似 Java 的扫描仪的流解析器?你可以去nextInt()获取intnextLong()获取long等。

【问题讨论】:

  • readf 应该适用于此
  • 我认为 readf 不会自动跳过空格。重点是自动使用空格作为分隔符并一次返回一个标记。 readf 两者都不做。

标签: java.util.scanner d


【解决方案1】:

std.conv.parse 类似: http://dlang.org/phobos/std_conv.html#parse

该示例是一个字符串,但也可以将其与其他字符源一起使用。

import std.conv;
import std.stdio;

void main() {
    // a char source from the user
    auto source = LockingTextReader(stdin);

    int a = parse!int(source); // use it with parse
    writeln("you wrote ", a);

    // munch only works on actual strings so we have to advance
    // this manually
    for(; !source.empty; source.popFront()) {
        auto ch = source.front;
        if(ch != ' ' && ch != '\n')
            break;
    }
    int b = parse!int(source);
    writeln("then you wrote ", b);
}

$ ./test56 12 23 你写了 12 然后你写了 23

【讨论】:

  • 这似乎是一种非常乏味的跳过空格的方法
  • 它可以很容易地放入一个函数中(只需记住将源作为ref 参数)
  • 您可以使用std.algorithm.stripLeft,它是std.string 的stripLeft 的相当新的通用版本。例如类似source = stripLeft!isWhite(source);
猜你喜欢
  • 2015-11-03
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 2015-12-14
  • 2010-10-31
  • 2017-07-15
相关资源
最近更新 更多