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)