开发者

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

开发者 https://www.devze.com 2023-03-07 16:58 出处:网络
I\'ve ran into an interesting problem. I have the following code: cout << \"\\nFILE\"; cout << \"\\tLocation:\" << file.location << endl;

I've ran into an interesting problem. I have the following code:

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

where location is set by a function that finds a file location in a file with the format

DRIVE:\dir1\dir2...\filename.extension

For example, the function will have successfully set file.location to

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

H开发者_如何学Goowever, the strangest thing happens. It outputs something that looks like this:

FILE

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

Location (c_str()): C:\Documents

Note the lack of the remaining file path. Being the astute programmer I am, I decided to test absolute paths. I physically set the string file.location to

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

and the corresponding output was

FILE

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

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

as expected. I then tested

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

and the output was

FILE

Location: C:Documents and Settingsadmintestfile.foo

Location (c_str()): C:Documents and Settingsadmintestfile.foo

also expected.

I cannot for the life of me figure out what could possibly be going wrong. The file path is clearly correct in the string itself, why would it change only in this case?


There are so many wrong things in your code... Here is the number 1 problem:

temp2 = char(HexToInt(temp2));

temp2 is empty at this point, so HexToInt returns 0.

Here are more problem:

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

this adds two char resulting in an int. It does not concatenate them. Use std::string::substr instead.

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

don't use floating point like this.

P.S. and this just demonstrates that you code is more important than your problem description.


I'm not quite sure I understand what exactly you're asking here, but I have a suggestion that can save you a lot of headache when manipulating paths: use Boost.Filesystem.Path. It will probably solve the problem you're having here as well. :)

Now, for your first case - if I understand correctly, file.location is an std::string. If you write it directly to a stream, it gives you the full string, but if you use c_str(), the string gets cut in the middle. That probably means you've got a NULL character in the middle of your string, after the document. I don't know why is that, but if you could post here the code that actually sets file.location, we may be able to help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号