2015-07-21 183 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