0

这看起来很简单。我基本上是在操作输入文本文件并尝试以特定格式输出文件。在我这样做之前,我需要$team->getWinsgetter 返回正确的值。输入文件的格式为队名、胜负。这是输入文本文件mlb_nl_2011.txt

Phillies 102 60
Braves 89 73
Nationals 80 81
Mets 77 85
Marlins 72 90
Brewers 96 66
Cardinals 90 72
Reds 79 83
Pirates 72 90
Cubs 71 91
Astros 56 106
DBacks 94 68
Giants 86 76
Dodgers 82 79
Rockies 73 89
Padres 71 91

这是Team.php文件:

<?php

class Team {

  private $name;
  private $wins;
  private $loss;

  public function __construct($name, $wins, $loss) {
    $this->name = $name;
    $this->wins = $wins;
    $this->loss = $loss;

    echo $this->name ." ";
    echo $this->wins ." ";
    echo $this->loss ."\n";
  }

  public function getName() {
    return $this->name;
  }

  public function getWins() {
    return $this->wins;
  }

  public function getLosses() {
    return $this->loss;
  }

  public function getWinPercentage() {
    return $this->wins / ($this->wins + $this->loss);
  }

  public function __toString() {
    return $this->name . " (" . $this->wins . ", " . $this->loss . ")";
  }

}

?>

这是我的主要PHP文件。

<?php

include_once("Team.php");

  $file_handle = fopen("mlb_nl_2011.txt", "r");

  $teams = array();
  $counter = 0;

  while(!feof($file_handle)) { 
            $line_data = fgets($file_handle);
            $line_data_array = explode(' ',trim($line_data));
            $team = new Team($line_data_array[0],$line_data_array[1],$line_data_array[2]);
            $teams[$counter] = $team;
            $counter++;
  }

  print_r($teams);
  //looks good through this point

  $output_file = "mlb_nl_2011_results.txt";
  $opened_file = fopen($output_file, 'a');

  foreach($teams as $team) {
    $win = $team->getWins();
    $los = $team->getLosses();
    echo $win ." ". $los."\n";
    $name = $team->getName();
    echo fprintf($opened_file, "%s  %d\n", $name, $win_per);
  }
  fclose($opened_file);

?>

在我做的时候print_r($teams),所有的值都是正确的。对于每个团队,我都会得到与此类似的打印:

[15] => Team Object
        (
            [name:Team:private] => Padres
            [wins:Team:private] => 71
            [loss:Team:private] => 91
        )

但是当我在打印时echo $win ." ". $los."\n";我得到了这个:

102 60
1289 73
1080 81
1377 85
872 90
1196 66
1190 72
1379 83
872 90
1171 91
856 106
1094 68
1086 76
1082 79
1173 89
1171 91

有任何想法吗??

4

1 回答 1

0

每行开头的意外数字(第一行除外)是此语句的结果...

echo fprintf($opened_file, "%s  %d\n", $name, $win_per);

...因为fprintf返回写入流的字符串的长度,echo并将此结果发送到标准输出(在这种情况下显然是屏幕)。因此,例如,您'12'打印了第二行,紧随其后的是'89 73\n'部分。

解决方案也很明显:摆脱echo这里。实际上,echo print ... ;在实际代码中使用构造很少是一个好主意。)

于 2013-09-02T02:39:21.660 回答