【发布时间】:2012-04-07 10:25:22
【问题描述】:
我在比较两个相同的 char 字符串时遇到问题:
char string[50];
strncpy(string, "StringToCompare", 49);
if( !strcmp("StringToCompare", string) )
//do stuff
else
//the code runs into here even tho both strings are the same...this is what the problem is.
如果我使用:
strcpy(string, "StringToCompare");
代替:
strncpy(string, "StringToCompare", 49);
它解决了问题,但我宁愿插入字符串的长度而不是它自己获取它。
这里出了什么问题?我该如何解决这个问题?
【问题讨论】:
-
错误的是你使用的是 c 字符串,而不是 std::string
-
“现实世界”中的字符串是否有可能是 49 个字符?
-
@VJovic 是什么让您如此确定 STL 在他的目标平台上可用?还是说不使用 STL 是他的决定?
-
@JamesMcLaughlin:首先,您可能在谈论 C++ 标准库,而不是 STL,它们是独立的库。其次,您知道 std::string 的任何非跨平台实现吗?它所需要的只是内存分配器,那么为什么它会依赖于平台呢?最后,为什么有人会避免使用 C++ 标准库并使用过时的 C 函数? 最好回到 C,因为 C++ 不再是“带类的 C”。
-
@Griwes 告诉 C 程序员 C 函数“已过时”...