c++ - 帮助 C++ 中的 ifstream 函数

标签 c++

我已经阅读了很多教程,但真的找不到关于这个主题的任何内容。

我写了下面的代码来完成一个功能:

#include <fstream>
#include <string>
#include <iostream>

using namespace std;

ifstream ReadFile( ifstream& openInputFile, string& sLine, int& chgLine );


int main()
{
    int chgLine;
    string MyFile, sLine, 
    sFile = "test.txt";

    cout << "Enter a file: ";
    cin >> MyFile ;

    ifstream openInputFile;


    if ( MyFile != sFile )    // file must be 'hello.cpp' to proceed
    {
       cout << "Error";
       exit(0);
    }
                         // if correct file is entered print the contents of it

        ReadFile( openInputFile, sLine, chgLine );

    system("pause");
    return 0;
}

ifstream ReadFile( ifstream& openInputFile, string& sLine, int& chgLine )
{ 

       while ( getline ( openInputFile, sLine ) )
       {
            if ( sLine.length() == 0 ) continue;  // to proceed

             for ( chgLine = 0; chgLine < sLine.length(); chgLine++ )
             {
                if ( sLine[chgLine] >= 97 && sLine[chgLine] <= 122 || sLine[chgLine] >= 65 && sLine[chgLine] <= 90  )
                {
                     cout << sLine[chgLine];
                }

             }
        }
}

但现在我决定将所有这些分解成三个函数,分别执行我想要的操作,然后从 main() 函数中调用它们。

第一个函数打开文件:

#include <iostream>
#include <fstream>
using namespace std;

ifstream openInputFile()

{
       // use a pointer..return a pointer
       // ifstream definition is the challenge
  ifstream *fp;
  //fp = new ifstream openInputFile;
  return openInputFile;

}

int main()

{
    cout << "Hello, world!" << endl;

    system("pause");
    return 0;
}

我在尝试返回指针时卡住了。我不明白我做错了什么。我怎样才能让最后一段代码工作?如果它具有函数的类型,如何使用 ifstream 返回一个指针?

最佳答案

执行此操作的 C++ 方法是创建一个包含所有打开、读取和写入的类。请注意,这也会处理自动关闭文件,RAII 的一个很好的例子。 .

// FancyFile.h:

class FancyFile
{
    private:
        std::ifstream stream;

    public:
        void DoMagic();

        InputFile(const std::string FilePath)
            { stream.open(FilePath.c_str()); }
        ~InputFile(void)
            { stream.close(); }
};
// FancyFile.cpp:

#include <fstream>
#include <string>

#include "FancyFile.h"

void FancyFile::DoMagic()
{
    //.. your custom file handling code goes here
}
// main:

#include "FancyFile.h"

int main()
{    
    FancyFile myFancyFile("test.txt");

    myFancyFile.DoMagic();

    system("pause");
    return 0;
}

关于c++ - 帮助 C++ 中的 ifstream 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/399053/

相关文章:

c++ - 试图让简单的 ODB 'hello' 程序工作

c++ - Cuda NVCC 编译器 - 如何/showincludes?

c++ - 在 C++ 中检查空指针的首选方法是什么?

c++ - 如何从 C++ 将字符串矩阵传递给 Cuda 内核

c++ - 无法将 nullptr 返回到我的类 C++

c++ - QT 5.5 setLayout() 通过返回值

c++ - 内存分配和复制构造函数

c++ - 没有重载函数需要 2 个参数(仿函数)

c++ - 如何使用添加到 MFC Doc/Frame 项目的对话框的初始化列表

c++ - 从同一个 VkPhysicalDevice 创建两个 VkDevices 是否有效?