将.txt文件中的字符串输出到成员方法局部作用域之外的动态数组

C++ Outputting strings from a .txt file in to a dynamic array outside of a member methods local scope

本文关键字:作用域 数组 动态 成员方法局 文件 txt 字符串 输出      更新时间:2023-10-16

首先,我问的是可能的吗?

我目前有一个具有一个成员方法(Read)的程序,该程序在一个成员方法中从本地的.txt文件中读取字符串,并将相同的数据输出到控制台。现在,我不能对数组的内容做任何事情,但是我需要在Write方法和代码中的其他任何地方使用数据。我使用了一个动态的C风格数组,因为这是我所需要的,不允许向量等。一个解决方案或任何一般的方向将是非常棒的!

我的结构由一个Main.cpp,一个ArrayStorage.cpp类定义和一个ArrayStorage.h头文件组成。

我的代码如下:

ArrayStorage.cpp

#include <fstream>
#include <iostream>
#include <ostream>
#include <string>
#include "ArrayStorage.h"
using namespace std;

void ArrayStorage::read(ifstream &fin1)
{
    int index = 0;
    int arrayLength = 0;
    string firstWord;
    if(fin1.is_open())
        {
            fin1 >> firstWord;
            fin1 >> arrayLength;
            string* arrayOfWords;
            arrayOfWords = new string[arrayLength];
            while(!fin1.eof())
            {
                fin1 >> arrayOfWords[index];
                cout << arrayOfWords[index];
                cout << "n";
                index++;
            }
            delete [] arrayOfWords;
            fin1.close();
        }
}
void ArrayStorage::write(ofstream &out1)
{
    //fout.close();
}

ArrayStorage.h

#include <fstream> // Reading/Writing from file requires this standard library.
#include <iostream> // Needed for cin and cout
#include <ostream> // Needed for outputting to output file
#include <string> // Needed for string values
using namespace std;
#pragma once
class ArrayStorage
{
private:

public:
    void read(ifstream &fin1); //reads data from a file
    void write(ofstream &out1); //output data to an output stream(ostream)
    bool exists(); //return true or false depending whether or not a given word exists
    void stdExists(); //^^ use either std::count() or std::find() inside here

};

Main.cpp

#include <fstream>
#include <iostream>
using namespace std;
#include "ArrayStorage.h"
#include "LinkedListStorage.h"

int main(int argc, char **argv) {
string find = "pixel";
ifstream fin1("ACW2_data.txt");
ofstream out1("1-In-SortedRead.txt");
if(!fin1.is_open()) 
{
    cout << "FAIL" << endl;
    return 1;
}
ArrayStorage arrayStorage1;
// read in values into data structure
arrayStorage1.read(fin1);
// output values in data structure to file
arrayStorage1.write(out1);
fin1.close();
out1.close();
return(0);
}

正如AnatolyS所说,应该使arrayOfWords成为类的私有成员变量。

然后确保没有内存泄漏或访问冲突错误,我建议如下:

  1. 在构造函数中初始化为NULL

    void ArrayStorage::ArrayStorage()
        : arrayOfWords(NULL)
    {}
    
  2. 在析构函数中删除它,如果它不是NULL

    void ArrayStorage::~ArrayStorage()
    {
        if (arrayOfWords)
            delete []arrayOfWords;
    }
    
  3. 当读取一个新文件时,如果使用同一个类读取多个文件(假设这是你想要的行为),请删除旧数组。

    if (arrayOfWords)
        delete []arrayOfWords;
    arrayOfWords = new string[arrayLength];
    
  4. 在你的"写"函数(或任何其他函数访问数组),检查它不是NULL之前,试图使用它。

你可以做的另一件事是检查"new"操作符是否返回NULL指针(如果内存不足可能会发生这种情况)。

这个例子说明了为什么像vector这样的类如此有用,因为它们为你处理了很多这样的分配/释放细节。