我遇到比较2个字符字符串都是同样的问题时:函数strncpy字符的字符串问题增加长度
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 – 2012-03-22 19:49:06
你必须添加字符串'\ 0'的结尾,因为您将“string”声明为字符的向量,而不是字符串。 – Cristy 2012-03-22 19:49:18
“真实世界”中的字符串是否有49个字符长? – 2012-03-22 19:53:34