读取文件并将其存储在C 中的保护变量中

Read file and store it in protected variable in c++

本文关键字:保护 变量 存储 文件 读取      更新时间:2023-10-16

我正在尝试读取文件并将其存储在受保护变量中。所有方法都在同一类中。

class A: public B
{
  public:
     //method declarations
  protected:
  string d;
};
void A::l(std::string filename)
{
  ifstream ifs;
  ifs.open(filename);
  string d { istreambuf_iterator<char> {ifs}, istreambuf_iterator<char> {} };  
  ifs.close();
 }
 void A::f(void)
 {
   std::cout << d.length()  << std::endl;
 }

当我尝试打印字符串的长度时,它是0。当我尝试在f()中打印 d时,什么也不会打印。我需要 d是一个受保护的变量,也不能更改方法。如何将读取文件字符串传递到f方法?

您分配给本地,使用成员(this->是可选的):

this->d.assign(istreambuf_iterator<char> {ifs}, {});

如果没有帮助,您可能会指定错误的文件名。

尝试一个绝对路径(例如/home/user/file.txt或c: documents user documents documents file.txt)>或检查程序的工作目录。

您可以随时检查错误:

if (!ifs) throw std::runtime_error("File could not be opened");

您的问题与您的变量受到保护无关。问题在于您正在定义另一个具有相同名称的变量。为了避免此问题,有些人将一个强调变量添加到变量的名称,例如" d_",其他人写下" m_d"。但是如果您不想,您就不需要这样做。

做您想做的一种方法是以下内容:

class A
{
  public:
  void l(std::string filename);
  void f();
 //method declarations
 protected:
 string d;

};

void A::l(std::string filename)
{
  ifstream ifs{filename};
  if(!ifs)
      return; // error
  std::copy(istreambuf_iterator<char>{ifs},
        istreambuf_iterator<char>{},
        std::back_inserter(d)); // this is A::d
}

您不需要使用'this->'。实际上,在C 中,您永远不会使用"此"(仅在诸如'return *this'之类的句子中)。

另外,在C 中,您不写:

void f(void);

但是,您写

void f();

,您也无需关闭ifstream。破坏者将为您做。