这是打开文件进行输入的正确方法吗?
这是打开文件进行输入的正确方法吗?
void BinaryTree::read(char * path, int line_number)
{
ifstream * file(path); //error: cannot convert ‘char*’ to ‘std::ifstream*’ in initialization
file->seekg(0, std::ios::beg);
int length = file.tellg();
char * buffer = new char[length];
file->getline(buffer, line_number);
printf("%d", length);
file->close();
}
我猜不会,因为编译器还不会接受 char
数组,或者 ifstream
构造函数的 std::string
当我阅读 文档 时,我看到 string
和/或 char 数组被传递给ifstream
构造函数。
我的编译器有问题还是我只是在参数中使用了错误的类型?
Is this the proper way to open a file for input?
void BinaryTree::read(char * path, int line_number)
{
ifstream * file(path); //error: cannot convert ‘char*’ to ‘std::ifstream*’ in initialization
file->seekg(0, std::ios::beg);
int length = file.tellg();
char * buffer = new char[length];
file->getline(buffer, line_number);
printf("%d", length);
file->close();
}
I'm guessing not, because the compiler won't accept a char
array, or a std::string
for the ifstream
constructor, yet when I read documentation, I see string
s and/or char
arrays being passed to ifstream
constructors.
Is something wrong with my compiler or am I just using the wrong type in my parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不要使用指针。这里不需要它。
试试这个:
然后将其用作:
Dont use pointer. It is not needed here.
Try this:
and then use it as:
问题在于对象的构造不合适。您可能正在尝试执行以下操作(或类似的操作),实际上将 char 数组传递给 ifstream 对象的构造函数:
但是,此处星号的引入改变了整个含义。您正在创建一个指向对象
ifstream
的指针,而不是对象ifstream
本身。为了构造一个指针,您需要另一个指向 ifstream 对象的指针(即相同类型的指针)。这不是您想要做的,无论如何,您可能想创建一个由指针引用的
ifstream
对象:但请记住,当不再需要该对象时,必须释放该对象。指针引用的对象不会像普通(堆栈中的对象)对象那样自动释放。
希望这有帮助。
The problem is that the construction of the object is not appropriate. You're probably trying to do the following (or something similar), indeed passing a char array to the constructor of the ifstream object:
However, the introduction of an asterisk here changes the whole meaning. You're creating a pointer to an object
ifstream
, but not the objectifstream
itself. And in order to construct a pointer, you would need another pointer to an ifstream object (i.e. a pointer of the same type).This is not what you intended to do, anyway, you probably wanted to create an
ifstream
object referenced by a pointer:But remember that the object must free'd when it is not needed anymore. Objects referenced by pointers are not automatically free'd as it happens with normal (objects in the stack) objects.
Hope this helps.
不需要指针,正如 @Nawaz 所说:
潜在的内存泄漏:
您应该随后删除它:
...但是,使用 std 更容易::string:
最终代码:
No pointer needed, as @Nawaz said:
Potential memory leak:
You should
delete[]
it afterwards:...But, it's a lot easier to use
std::string
:Final code:
不过,您遇到的问题比上面提到的问题更多:
抱歉,如果我错过了这里的要点
You've got more problems than the ones mentioned above though:
apologies if I've missed the point here
我要改变的几件事:
这里简化:
Couple of things I would change:
Simplified here: