mereth
mereth

Reputation: 495

Can't append string more than once in c++

I am trying to append more strings together, when I use append once, it works fine, but after using it again it fails.

camName = "./XML//X";
std::string camera1 = "cam1";
camName.append(camera1);

This gives me string ./XML//Xcam1 and it's fine.

camName = "./XML//X";
std::string xml = ".xml";
camName.append(xml);

This also gives a good result -> ./XML//X.xml

But then I tried to do both:

camName = "./XML//X";
std::string camera1 = "cam1";

camName.append(camera1);
std::string xml = ".xml";

camName.append(xml);

I expected this to give me -> ./XML//Xcam1.xml

But instead I get something like this -> ≡┼2U_

EDIT: This is my whole function:

#include <string>
using std::string;

bool MyStitcher::checkCameras(string c1, string c2, string c3, string c4, string c5, string c6) {
    string camName = "./XML//X";

    if (c1 != "a") {
        camName.append(c1);
    }
    else if (c2 != "a") {
        camName.append(c2);
    }
    else if (c3 != "a") {
        camName.append(c3);
    }
    else if (c4 != "a") {
        camName.append(c4);
    }
    else if (c5 != "a") {
        camName.append(c5);
    }
    else if (c6 != "a") {
        camName.append(c6);
    }

    std::string xml = ".xml";
    camName.append(xml);

    printf("name %s\n", camName);

    if (FILE *file = fopen(camName.c_str(), "r")) {
        fclose(file);
        return true;
    }
    else {
        return false;
    }
}

If one of the if statements is true, i get weird result(c1,c2,... are strings like "cam1" etc.)

Upvotes: 1

Views: 204

Answers (2)

JVApen
JVApen

Reputation: 11317

The problem on hand is an incorrect use of printf As printf is a C-function, it has some limitations.

In this specific case, it contains C-style variadic arguments. Calling such a function with a non-POD (plain old data) is undefined behavior. In this case, it seems to be your compiler is reinterpret casting the std::string.

Because std::string has a short string optimization, this seems to working until you have too many characters in it.

There are 2 ways of solving this:

printf("name %s\n", camName.c_str());

This will get the char* from the string, which is also known by C and will work. However, printf also has has a C++ variant in which it is less likely to have conversion issues: cout

std::cout << "name " << camName << std::endl;

Upvotes: 1

Alan Birtles
Alan Birtles

Reputation: 36389

printf("name %s\n", camName);

should be

printf("name %s\n", camName.c_str());

Upvotes: 3

Related Questions