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

时间:2011-05-21 10:46:26

标签: c++ string stl runtime-error filepath

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

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

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

的文件中查找文件位置
  

DRIVE:\ DIR1 \ DIR2 ... \ filename.extension

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

  

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

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

  

FILE

     

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

     

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

请注意缺少剩余的文件路径。作为精明的程序员,我决定测试绝对路径。我将字符串file.location设置为

  

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

,相应的输出是

  

FILE

     

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

     

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

正如所料。然后我测试了

  

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

,输出

  

FILE

     

位置:C:Documents and Settingsadmintestfile.foo

     

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

也在期待。

我不能为我的生活找出可能出错的地方。文件路径在字符串本身中显然是正确的,为什么它只会在这种情况下改变?

2 个答案:

答案 0 :(得分:2)

我不太确定我明白你在这里问的是什么,但我有一个建议可以在操纵路径时为你节省很多麻烦:使用Boost.Filesystem.Path。它可能会解决你在这里遇到的问题。 :)

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

答案 1 :(得分:2)

your code中有太多错误的东西......这是第一个问题:

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);

不要像这样使用浮点数。

P.S。这只是证明你的代码比你的问题描述更重要。

相关问题