我想通过定义一个新类
ifstream
来扩展ifstreamExt
,其中:
有一个名为“directory”的类变量,它是一个字符串,保存文件将打开的位置。
重新定义了 open 方法,以便使用
directory
变量。
最后,
>>
应该至少可以与字符串一起使用。
我成功地做到了 1 和 2 - 但我失败了 3。我不知道如何写它,我做了多次尝试。第一个是使用
getline
,效果很好,但不如 >>
有效;该运算符会跳过空格并检索连续的非空格字符,而 getline 会获取整行并且不会选取每个子字符串。
class ifstreamExt : ifstream {
public:
void open(string f) {
string s = h + "/" + f;
name = s;
if (!is_open()) {
cerr << "cannot open " << s << endl;
exit(1);
} else {
cerr << "open file " << s << endl;
}
}
friend ifstreamExt & operator >> (ifstreamExt & is, string &str) {
}
static void set_directory(string d) {
cerr << "set home directory : " << d << endl;
h = d;
DIR* dir = opendir(h.c_str());
if (dir) {
cerr << "directory " << h << " exists " << endl;
} else {
cerr << "directory " << h << " does not exist " << endl;
exit(1);
}
}
private :
static string h;
};
根据评论中发布的建议,这里是 ifstreamExt,它是一个具有组合的新类。欢迎任何反馈!
class ifstreamExt {
public :
ifstreamExt() : file_() { }
void open(const std::string &filename) {
string f_name = _dir_ + "/" + filename;
file_.open(f_name);
if (!file_.is_open()) {
cerr << "cannot open " << f_name << endl;
exit(1);
} else {
cerr << "open " << f_name << endl;
}
}
void close(void) {file_.close();}
bool is_open() {return file_.is_open();}
friend ifstreamExt& operator >> (ifstreamExt & is, string &str) {
is.file_ >> str;
return is;
}
static void set_directory(string d) {
_dir_ = d;
}
private:
std::ifstream file_;
static string _dir_;
};