在c ++中不能多次追加字符串

问题描述 投票:1回答:2

我试图将更多字符串附加在一起,当我使用append一次时,它工作正常,但在再次使用它之后就失败了。

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

这给了我字符串./XML//Xcam1,没关系。

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

这也给出了一个很好的结果 - > ./XML//X.xml

但后来我试着这两个:

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

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

camName.append(xml);

我希望这能给我 - > ./XML//Xcam1.xml

但相反,我得到这样的东西 - >≡┼2U_

编辑:这是我的全部功能:

#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语句为真,我得到奇怪的结果(c1,c2,...是像“cam1”等字符串)

c++ string append
2个回答
1
投票

手头的问题是printf的错误使用由于printf是一个C函数,它有一些局限性。

在这种特定情况下,它包含C风格的可变参数。用非POD(普通旧数据)调用这样的函数是undefined behavior。在这种情况下,它似乎是你的编译器重新解释铸造std::string

因为std::string有一个short string optimization,这似乎有效,直到你有太多的字符。

有两种方法可以解决这个问题:

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

这将从字符串中获取char*,这也是C所知的并且可以工作。但是,printf也有一个C ++变体,它不太可能有转换问题:cout

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

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

应该

printf("name %s\n", camName.c_str());
© www.soinside.com 2019 - 2024. All rights reserved.