?要实现这种效果, 读取键盘输入
* index.php
<?php
include "Scanner.php";
class Solution {
public static function main() {
// $sc = new Scanner("php://stdin");
$sc = new Scanner("./input/input.txt");
while ($sc->hasNext()) {
$rn = $sc->nextInt();
printf("---- rn=%d ----\n", $rn);
// fflush(STDOUT);
}
}
}
Solution::main();
命令行读取键盘输入, 文件路径填写 “php://stdin”
如果是http请求,文件路径填写 “php://input”
* Scanner.php
<?php
class Scanner {
/** @var resource */
protected $in;
/**
* Scanner constructor.
* @param $uri "php://input", "file:///D:/Users/mingz/CLionProjects/nowcoder/huawei/core.txt"
*/
public function __construct(/* string */$uri) {
$this->in = fopen($uri, 'r');
}
private static function isBlank($c) {
return strncmp($c, " ", 1) == 0 || strncmp($c, "\t", 1) == 0
|| strncmp($c, "\r", 1) == 0 || strncmp($c, "\n", 1) == 0;
}
/**
* Get a word from resource $this->in, char by char
* @return string
*/
private function getWord() {
$ch = fgetc($this->in);
for (; !feof($this->in); $ch = fgetc($this->in)) {
if (!self::isBlank($ch)) {break;}
}
// $at = ftell($this->in);
$word = "";
for (; !feof($this->in); ) {
if (self::isBlank($ch)) {
break;
} else {
$word .= $ch;
}
$ch = fgetc($this->in);
}
return $word;
}
private function _next() {
return $this->getWord();
}
private static function atoi($s) {
$num = 0;
$i = 0;
for (; isset($s[$i]); $i += 1) {
if (!self::isBlank($s[$i])) {break;}
}
$codeMinus = ord("-");
$negative = false;
if (ord($s[$i]) == $codeMinus) {
$negative = true;
$i += 1;
}
$codeDot = ord(".");
for (; isset($s[$i]); $i += 1) {
$code = ord($s[$i]);
if (48 <= $code && $code < 58) {
$num = 10 * $num + ($code - 48);
} elseif ($code == $codeDot) {
break;
}
if ($num > PHP_INT_MAX) {
throw new OutOfRangeException("Integer out of range: ".PHP_INT_MAX);
}
}
if ($negative) {$num = 0 - $num;}
return $num;
}
public function nextInt() {
$nextWord = "";
for (;;) {
$nextWord = $this->_next();
if (is_numeric($nextWord)) {break;}
}
return self::atoi($nextWord);
}
public function next() {return $this->_next();}
public function hasNext() {
return !feof($this->in);
}
public function __destruct() {fclose($this->in);}
// -- for debug ---
private static function bufDump(/* string */$buf) {
if (!isset($buf[0])) {return "{}";}
$n = strlen($buf);
$s = "{". $buf[0];
for ($i = 1; $i < $n; $i++) {
$ch = $buf[$i];
if ($ch == "\r") {$ch = "\\r";}
else if ($ch == "\n") {$ch = "\\n";}
$s .= "|". $ch;
}
return $s . "}";
}
private static function arrDump($a) {
if (empty($a)) {return "[]";}
$s = "[". $a[0];
for ($i = 1; isset($a[$i]); $i += 1) {
$s .= ",".$a[$i];
}
return $s."]";
}
}
使用buffered reader很麻烦,一个字符一个字符读取算了
|