std::string 到 str::string.c_str() 与文件路径的转换中存在有趣的问题

Interesting problem in std::string to str::string.c_str() conversion with file paths

本文关键字:str string 转换 存在 问题 路径 std 文件      更新时间:2023-10-16

我遇到了一个有趣的问题。我有以下代码:

cout << "nFILE";
cout << "tLocation:" << file.location << endl;
cout << "tLocation (c_str()): " << file.location.c_str() << endl;

其中位置由一个函数设置,该函数在格式为

驱动器:\dir1\dir2...\文件名.扩展名

例如,该函数将成功将 file.location 设置为

C:\Documents and Settings\admin\testfile.foo

然而,最奇怪的事情发生了。它输出的内容如下所示:

文件

位置: C:\Documents and Settings\admin\testfile.foo

位置 (c_str(((: C:\Documents

请注意缺少剩余的文件路径。作为一个精明的程序员,我决定测试绝对路径。我物理地将字符串文件位置设置为

C:\\Documents and Settings\\admin\\testfile.foo

相应的输出为

文件

位置: C:\Documents and Settings\admin\testfile.foo

位置 (c_str(((: C:\Documents and Settings\admin\testfile.foo

不出所料。然后我测试

C:\Documents and Settings\admin\testfile.foo

输出是

文件

位置: C:Documents and Settingsadmintestfile.foo

位置 (c_str(((: C:Documents and Settingsadmintestfile.foo

也意料之中。

我一辈子都无法弄清楚可能出了什么问题。字符串本身的文件路径显然是正确的,为什么它只会在这种情况下更改?

你的代码中有很多错误的东西......这是第一个问题:

temp2 = char(HexToInt(temp2));

此时temp2为空,因此HexToInt返回 0。

这里有更多的问题:

temp = Location[i+1] + Location[i+2]; 

这将添加两个char,从而导致int。它连接它们。请改用std::string::substr

temp += j * pow(16.00, k);

不要像这样使用浮点数。

附言,这只是表明您的代码比您的问题描述更重要。

我不太确定我是否理解您在这里问的确切内容,但是我有一个建议,可以在操作路径时为您省去很多麻烦:使用Boost.Filesystem.Path。它也可能解决您在这里遇到的问题。:)

现在,对于您的第一种情况 - 如果我理解正确,file.location是一个 std::string。如果你直接把它写到流,它会给你完整的字符串,但如果你使用c_str(),字符串会在中间被切断。这可能意味着您在文档之后的字符串中间有一个 NULL 字符。我不知道为什么会这样,但是如果您可以在此处发布实际设置file.location的代码,我们也许可以为您提供帮助。