gpt4 book ai didi

C++ Ifstream 读太多?

转载 作者:太空狗 更新时间:2023-10-29 23:33:59 24 4
gpt4 key购买 nike

我正在尝试读取文件并输出内容。一切正常,我可以看到内容,但最后似乎添加了大约 14 个空字节。有谁知道这段代码有什么问题吗?

                    int length;
char * html;


ifstream is;
is.open ("index.html");
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
html = new char [length];

is.read(html, length);
is.close();
cout << html;
delete[] html;

最佳答案

您没有在 char 数组上放置空终止符。不是 ifstream 读取太多,cout 只是没有空终止符不知道什么时候停止打印。

如果你想读取整个文件,这会容易得多:

std::ostringstream oss;
ifstream fin("index.html");
oss << fin.rdbuf();
std::string html = oss.str();
std::cout << html;

关于C++ Ifstream 读太多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7049214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com