奇怪的c++字符串连接行为

Strange C++ string concatenation behaviour

本文关键字:连接 字符串 c++      更新时间:2023-10-16

我一直注意到字符串连接的这种奇怪行为,尽管strcmp返回零,表明两种形式是相同的

包含文件options.h如下所示

struct options = {
   std::string ctifile;
   ...
};

主文件以两种方式写入

方法1

#include "options.h"
#include <string>
#include "cantera/IdealGasMix.h"
options opt = {
  "mech/tot.cti"
};
IdealGasMix gas(opt.ctifile, ...);

在第二个方法中,

#include "options.h"
#include <string>
#include "cantera/IdealGasMix.h"
options opt = {
  "tot.cti"
};
IdealGasMix gas(std::string("mech/") + opt.ctifile, ...);

由于某种原因,只有方法2无法找到指定的文件。指针吗?(一语双关)

strcmp期望cstring,您可以通过

std::string x = "blah blah";
assert(strcmp(x.c_str(), x.c_str()) == 0);

但是如果你使用std::strings为什么不直接使用std::string::compare

std::string x = "blah blah";
assert(x.compare(x) == 0);
http://www.cplusplus.com/reference/string/string/compare/

警告:如果你试图做比较unicode字符串那么简单的STRCMP可能并不总是工作