std::string 到 str::string.c_str() 与文件路径的转换中存在有趣的问题
Interesting problem in std::string to str::string.c_str() conversion with file paths
我遇到了一个有趣的问题。我有以下代码:
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的代码,我们也许可以为您提供帮助。
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- Python str to C++ to Python str
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 在 c++ 中使用" for(string str: tmp) "?
- String & String::Concat(const char Str[])
- Boost.Python.ArgumentError:Python str未转换为std::string
- getline 的实现 ( istream&is, string&str )
- Why std::string str = {}?
- 为什么stringstream::str()截断string
- 使用 string.find() 确定第 i 个"str"的位置
- std::string 到 str::string.c_str() 与文件路径的转换中存在有趣的问题
- c++:以std::string (&str[0])作为缓冲区安全地读取文件
- Str.compare()或(string)A == (string)B用于字符串比较