0

I want to concatenate three string in C++.

I have a vector std::vector<std::string> my_list where the filenames are stored. I want to add the directory and filename extension for each of the filenames in order to read binary the information from the file, so i do it like that:

for (int i = 0; i < my_list.size(); i++) {
        std::string tmp = prefix + my_list[i] + suffix;
        std::ifstream file(tmp.c_str(), std::ifstream::binary);
}

where prefix ist std::string prefix = "directory/" and suffix ist std::string suffix = ".foo".

And it works in Windows. However it doesn't work in Linux. Suffix overwrites "tmp"-string. It looks like foo/y_file_timestamp instead of out/my_file_timestamp.foo.

What should I do to prevent this overwriting?

KTBFFH
  • 65
  • 1
  • 8

2 Answers2

7

The bug is not in the code you showed us.

The problem is that your strings have unexpected characters in them, specifically carriage returns ('\r') that cause the caret to return to the beginning of the line during output of your concatenated string to the terminal window.

Presumably this is a problem caused by careless parsing of input data with Windows-style line endings. You should normalise your data and be sure to strip all line-ending variants during parsing.

Always be sure to check the contents of your strings at the character-level when encountering a problem with string operations.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Thank you @BarryTheHatchet. I forgot to mention that vector my_list was filled this way:

std::string LIST_WITH_DATA = "data/list.scp"

const char* my_data = LIST_WITH_DATA.c_str();

std::ifstream my_file(my_data);

std::string my_line;

while (std::getline(my_file, my_line)) {

    my_list.push_back(my_line);

}

data/list.scp looks like:

file1/00001-a
file2/00001-b
file3/00001-c
file4/00001-d

std::getline was my problem.

The solution I found here: Getting std :: ifstream to handle LF, CR, and CRLF?

Community
  • 1
  • 1
KTBFFH
  • 65
  • 1
  • 8