简体   繁体   中英

std::string += operator

I'm having a bad couple of days for odd behaviour. I have a std::string on which I use the += operator to add another string (actually the name of a file being appended to a path). When I run the program I have found that the file was not being found. Copious couts later have revealed that I am getting the file name added to the start of the string.

std::string path("/home/me/location/");
std::string file("file.txt");
path += file;
std::cout << path.c_str();

The output from this is "file.txt/location"!!! I have tried a simple program which just adds two strings together and that works fine which I was expecting (gcc v 4.3). I have copied the code over from a windows machine, I wasn't expecting any issues beyond new file paths, it only really uses STL and dirent, indeed it compiled more or less first time. I ran dos2unix just in case. Now I'm a little bit stumped but I haven't really copied code over before beyond the totally trivial so I might be missing something blindingly obvious.

Is the pathname somehow getting a "\\r" appended to it, so that when you print it to cout it prints "/home/me/location/", returns to the start of the line, then prints "line.txt"?

As someone said, look at the variables with a debugger. (My instincts are for logging/printing too, but debuggers are useful too)

What you're missing is the / separator between the directory name and the file name.

Otherwise there is nothing wrong with the code you've posted.

One thing to bear in mind is that your code modifies the path variable. If you do path += file repeatedly for different file names, make sure to re-initialize path every time.

PS There is no way the four lines of code that you've posted can print out file.txt/location . Either the code that you've posted differs from what you're running, or the output isn't the same.

It looks like file starts with a carriage return . If this is the case, += would still append file to path , but when the string is cout'ed, it would display the behaviour you describe.

You should use std::stringstream for this:

std::stringstream tempss;
std::string path("/home/me/location");
std::string file("file.txt");

tempss << path;
tempss << file;

std::string filepath = tempss.str();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM