C++ ifstream has incomplete type

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 12:38:20

问题


I'm modifying an project where I want to write an output to a file. In my .hpp file I declared a file stream like so:

// fname.hpp file
#include <fstream>

std::ifstream m_ifs = ("path_to_file");

then on my .cpp file I am have

// fname.cpp
if (!m_ifs.is_open()) {
      std::cerr << "Not writing to file" << std::endl;
      return;
}
m_ifs << "Write something"

But when I compile I get the following error:

error: field ‘m_ifs’ has incomplete type ‘std::ifstream {aka std::basic_ifstream<char>}’

/usr/include/c++/5/iosfwd:116:11: note: declaration of ‘std::ifstream {aka class std::basic_ifstream<char>}’
     class basic_ifstream;

The error points to my declaration on the hpp file.

The solutions I found on the web didn't solve the problem.


The following worked:

// fname.hpp file
#include <fstream>

const std::string m_file = ("path_to_file");
std::fstream m_fs;

and

// fname.cpp
m_fs.open(m_file.c_str());
if (!m_fs.is_open()) {
      std::cerr << "Not writing to file" << std::endl;
      return;
}
m_fs << "Write something"

回答1:


It looks like a global variable to me. If it indeed is, declare them the following way:

//fname.hpp:
const std::string m_file = ("path_to_file");
std::fstream m_fs;

and

// fname.cpp
m_fs.open(m_file.c_str());
if (!m_fs.is_open()) {
      std::cerr << "Not writing to file" << std::endl;
      return;
}
m_fs << "Write something"

Also, you can't write to ifstream. Change it to ofstream or fstream.




回答2:


It looks like you got ifstream and ofstream confused. As was stated in the comments, std::ifstream does not define the operator <<.

What you are looking for with an output file is std::ofstream. Remember the o is for output, i is for input



来源:https://stackoverflow.com/questions/50841816/c-ifstream-has-incomplete-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!