gpt4 book ai didi

C++ - 字符串流 << "overwriting"

转载 作者:行者123 更新时间:2023-12-03 06:55:18 25 4
gpt4 key购买 nike

我正在用 C++ 制作 OpenGL 游戏。与其他语言相比,我在 C++ 方面相当缺乏经验。无论如何,我为一些图像创建了一个带有“基本”目录的字符串流。然后,我将此字符串流作为函数参数传递给构造函数。构造函数附加一个图像文件名,然后尝试加载结果路径。然而……

D:\CodeBlocks Projects\SnakeRoid\bin\Debug\Texts\ <-- before appending the filename
Ship01.tgacks Projects\SnakeRoid\bin\Debug\Texts\ <-- After.

显然不正确!结果应该是D:\CodeBlocks Projects\SnakeRoid\bin\Debug\Texts\Ship01.tga

我的代码的相关部分:

std::stringstream concat;
std::string txtFullPath = "Path here";

...

concat.str(""); //Reset value (because it was changed in ...)
concat << texFullPath; //Restore the base path
PS = new PlayerShip(&TexMan, concat); //Call the constructor

构造函数的代码

PlayerShip::PlayerShip(TextureManager * TexMan, std::stringstream &path)
{
texId = 2;
std::cout << path.str(); //First path above
path << "Ship01.tga";
std::cout << path.str(); //Second - this is the messed up one
//Do more fun stuff
}

有人知道为什么它会“覆盖”字符串流中已有的内容吗?

最佳答案

why its "overwriting" what's already in the stringstream

因为输出将字符放置在输出缓冲区中的“放置指针”位置。新构造的流将 put 指针设置为零(以追加模式打开的文件输出流除外),因此您的输出会覆盖缓冲区中已有的字符。

如果您确实需要以这种方式追加字符串,则需要将 put 指针移动到缓冲区的末尾:

std::cout << p.str(); //First path above
std::stringstream path;
path.str(p.str());
path.seekp(0, std::ios_base::end); // <-- add this
path << "Ship01.tga";
std::cout << "Loading player ship from " << path.str();

编辑:问题已被编辑,编辑后的代码有效,因为它不再使用 path.str(p.str()); 在不使用输出的情况下创建输出缓冲区操作(并且不推进 put 指针):参见 ideone差异。

在任何情况下,字符串本身都可以连接起来,这将使代码更易于理解:

std::string p = path.str() + "Ship01.tga";
std::cout << p;

更不用说处理文件和路径名了,我们有boost.filesystem .

关于C++ - 字符串流 << "overwriting",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63959925/

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