2015-07-21 70 views
0

空间我有一个看起来像这样良好的输入文件:混乱与FILEIO

734 220 915 927 384 349 79 378 593 46 2 581 500 518 556 771 697 
571 891 181 537 455 

和坏输入文件看起来像这样:

819 135 915 927 384 349 79 378 593 46 2 581 500 518 556 771 697 
551 425 815 978 626 207 931 ABCDEFG 358 16 875 936 899 885 195 565 
571 891 181 537 110 

那里是最后一个整数以下的空间在两个文件的末尾。我试图用C++编写一个脚本,它将读取所有整数,除非第二个例子中有一个字符/字符串,在这种情况下,它会提醒我这一点。我试图把它写这样的:

int main() 
{ 
int n; 
bool badfile = false; 
ifstream filein("data.txt"); 

while (!filein.eof()) 
{ 
    filein >> n;  
    if(filein.fail()) 
    { 
     cout << "Not an integer." << endl; 
     badfile = true; 
     break; 
    } 
    cout << n << " "; 
} 

cout << endl << "file check: " << badfile << endl; 
} 

filein.fail()是在一个良好的文件末尾的空间,以及在一个坏的文件中的字符/串触发。那么我怎样才能设置它以忽略空白?为什么只有在最后有一个空间而不是在所有空间都失败或者完全忽略它们时才会失败?

回答

1

的主要问题是你如何测试eof()在流...它只能设置后输入尝试尝试的时候就已经在文件的结尾读取多个字符。首先使用std::ws来消耗空白意味着eof检测可能是可靠的:如果您不在eof()那么您知道您在某些非空白输入应该是数字 - 如果不是,则输入内容中有错误。

建议代码:

#include <iostream> 
#include <fstream> 
#include <iomanip> 

int main() 
{ 
    if (ifstream filein("data.txt")) 
    { 
     while (filein >> std::ws && !filein.eof()) 
     { 
      int n; 
      if (filein >> n) 
       cout << n << ' '; 
      else 
      { 
       std::cerr << "error in input\n"; 
       exit(EXIT_FAILURE); 
      } 
     } 
     std::cout << '\n'; 
    } 
    else 
     std::cerr << "unable to open data.txt\n"; 
} 

另一种出现在下方,这可能是比较容易理解,但不是完全可靠。问题在于,尽管输入错误(例如-+)可能会导致EOF失败,因为在尝试读取数字时会消耗这些数据,但本身并不足以成功解析数字。只有当文件被称为具有'\n'终止的最后一行,这将是可靠的:

 int n; 
     while (filein >> n) 
      cout << n << " "; 
     filein.clear(); // remove the error state 
     if (filein.peek() != istream::traits_type::eof()) 
     { 
      // while didn't reach EOF; must be parsing error 
      std::error << "invalid input\n"; 
      exit(EXIT_FAILURE); 
     } 
+0

嗯..这个工作,但我真的不明白因为它使用std中比我迄今为止学到的更先进的东西。有没有更基本的方法来做到这一点?此外,我仍然困惑,为什么它首先导致问题。我更多地将它作为一个初学者在fileIO中的学习练习,而不是试图找到一个快速修复的工具。 – Austin

+1

@AustinMW:有更多的细节为什么'while(!in.eof())'被打破[这里](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-条件考虑的,是错误的)。还有另一种方法,您可能会也可能不会找到更简单的方法,我会将其添加以供您考虑。干杯。 –

0

我建议

ifstream filein("data.txt"); 
while (filein >> n) 
    cout << n << " "; 
if (filein.fail()) { 
    cout << "Not an integer." << endl; 
    badfile = true; 
} 
cout << endl << boolalpha << badfile << endl; 
+0

这会返回“不是整数”。 badfile == true表示良好的数据文件。以为会有一个类似这样的简单方法,但我猜不是。虽然知道'boolalpha',但还没有看到。 – Austin