首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >奇怪的C++字符串连接行为

奇怪的C++字符串连接行为
EN

Stack Overflow用户
提问于 2016-10-09 02:33:58
回答 1查看 70关注 0票数 0

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

包含文件options.h如下所示

代码语言:javascript
复制
struct options = {
   std::string ctifile;
   ...
};

主文件以两种方式写入

方法1

代码语言:javascript
复制
#include "options.h"
#include <string>
#include "cantera/IdealGasMix.h"

options opt = {
  "mech/tot.cti"
};

IdealGasMix gas(opt.ctifile, ...);

在第二方法中,

代码语言:javascript
复制
#include "options.h"
#include <string>
#include "cantera/IdealGasMix.h"

options opt = {
  "tot.cti"
};

IdealGasMix gas(std::string("mech/") + opt.ctifile, ...);

由于某些原因,只有方法2无法找到指定的文件。有什么建议吗?(双关语)

EN

回答 1

Stack Overflow用户

发布于 2016-10-09 02:48:20

strcmp需要cstring,您可以通过下面的命令获得

代码语言:javascript
复制
std::string x = "blah blah";
assert(strcmp(x.c_str(), x.c_str()) == 0);

但是如果你正在使用std::string,为什么不直接使用std::string::compare呢

代码语言:javascript
复制
std::string x = "blah blah";
assert(x.compare(x) == 0);

http://www.cplusplus.com/reference/string/string/compare/

警告:如果您尝试比较unicode字符串,那么简单的strcmp可能并不总是有效的

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39935939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档