2016-04-07 38 views
0

我有一個工作要做的C + +,它假設讀取一個文件.txt並使用裏面的信息。但是,我們的老師給了我們開始的代碼來幫助,我真的不明白。我是C++的初學者,所以我一直在尋找它幾個小時,但我還沒有找到答案,謝謝!不明白這段代碼?這是關於閱讀一個文件在C++

下面是一段代碼:

int main(int argc, const char** argv) 
{ 
    std::ifstream* myfile = NULL; 

    if (argc == 2) { 
     file = myfile = new std::ifstream(argv[1]); 
     if (myfile->fail()) 
      std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl; 
    } 
    else 
     std::cerr << "No file name." << std::endl; 

    while (*file) { 
     std::string event; 
     *file >> event; 
     if (!(*file)) break; 

     if (event == "recipe") { 
      std::string namerecipe; 
      *file >> recipe; 

...

洙我不明白這一點?什麼是*文件?和文件?它是文件上的指針嗎?爲什麼沒有任何功能可以讓線路工作呢?爲什麼「while *文件」應該這樣做? 非常感謝!

+0

你知道指針是什麼? – immibis

+0

我懷疑這個代碼是故意瘋狂的。 – user4581301

+1

等一下。你的老師動態地分配'std :: ifstream'嗎?要麼我錯過了一些東西,要麼有特殊的教學目的,或者老師不擅長編程。 –

回答

1
int main(int argc, const char** argv) 
{ 

一個典型的函數入口點。

std::ifstream* myfile = NULL; 

    if (argc == 2) { 

確保有足夠的參數從argv[1]獲取文件名。

 file = myfile = new std::ifstream(argv[1]); 

動態分配一個文件輸入流,並試圖用它來打開在argv[1]指定的文件。然後將該文件流分配給兩個指針filemyfile。我承認沒有看到有兩個指針的意思,但我也沒有看到指針的重點。

 if (myfile->fail()) 

調用流的fail函數。這測試是否有任何錯誤的流。此時所有要測試的是流是否打開。

  std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl; 
    } 
    else 
     std::cerr << "No file name." << std::endl; 

    while (*file) { 

取消引用的file指針文件對象上操作。這將會調用流的布爾運算符。這與C++ 11或更近的C++相同,或者在這種情況下(在C++ 11之前)無關緊要,因爲調用!file->fail()。更多關於運營商布爾這裏:http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool

 std::string event; 
     *file >> event; 

讀一個空格分隔的令牌,一個字,從流。

 if (!(*file)) break; 

運算符再次布爾。失敗時退出循環。

 if (event == "recipe") { 
      std::string namerecipe; 
      *file >> recipe; 

從該信息流中讀取另一個字。

的代碼可以沿着這些線路重新編寫:

int main(int argc, const char** argv) 
{ 
    if (argc == 2) 
    { 
     std::ifstream myfile(argv[1]); 
     if (myfile) 
     { 
      std::string event; 
      while (myfile >> event) 
      { 
       //this function is getting deep. Consider spinning this off into a new function 
       if (event == "recipe") 
       { 
        std::string namerecipe; 
        if (myfile >> recipe) 
        { 
         // do stuff that is missing from code sample 
        } 
        else 
        { 
         // handle error 
        } 
       } 
      } 
     } 
     else 
     { 
      std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl; 
     } 
    } 
    else 
    { 
     std::cerr << "No file name." << std::endl; 
    } 
} 
+0

謝謝,我真的很感謝你幫助我!我想我現在得到了,你的解釋非常清楚 – robbie

0
  1. *file是您的指針,指向輸入文件流ifstream對象。
  2. file是您的輸入文件流ifstream對象。

  3. while(*file)使用流的布爾運算符來測試輸入文件流錯誤條件(在閱讀,沒有錯誤的文件)

+0

點3不正確。它不測試NULL,它使用流的布爾運算符來測試流中的錯誤條件。 – user4581301

+0

@ user4581301我認爲這就像我們迭代鏈表一樣。恩姆感謝我將編輯它的教訓。你能澄清更多嗎? –

+1

它是'while(!file-> fail())'的簡寫。更多在這裏:http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool(我應該改正,在C++ 11中是簡寫,以前它只是相似的) – user4581301