2016-04-07 36 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