hangaozu
 1 #include <fstream>
 2 ifstream inFile;    //ifstream类的inFile对象
 3 
 4 double value;
 5 inFile >> value;
 6 while(inFile.good())
 7 {
 8     //loop body goes here10     inFile >> value;
11 }    

这是原始版本代码,方法good()指出最后一次读取输入的操作是否成功,这一点至关重要. 这意味着应该在执行读取输入的操作后,立刻应用这种测试。为此,一种标准方法是,在循环之前(首次执行循环测试前)放置一条输入语句,并在循环的末尾(下次执行循环测试之前)放置另一条输入语句。

 

鉴于以下事实,可以对上述代码进行精简:表达式 inFile >> value 的结果为inFile,而在需要一个bool结果值的情况下,inFile的结果又可以为inFile.good(),即true 或者 false。

因此有了下面的精简后的代码:

1 #include <fstream>
2 ifstream inFile;    //ifstream类的inFile对象
3  
4 double value;
5 while(inFile >> value)
6 {
7     //loop body goes here   
8 } 

 

这种设计仍然遵循了在测试之前进行读取的规则,因为要计算表达式inFile >> value的值,程序必须首先试图将一个数字读取到value中。

分类:

C++

技术点:

相关文章:

  • 2022-12-23
  • 2021-11-11
  • 2021-12-29
  • 2021-08-09
  • 2021-09-16
  • 2022-12-23
  • 2021-11-23
  • 2021-07-05
猜你喜欢
  • 2021-07-15
  • 2021-07-18
  • 2021-11-06
  • 2021-11-23
  • 2021-04-08
  • 2022-12-23
相关资源
相似解决方案