c ++ strtok在函数中将原始字符串值更改为参数 [英] c++ strtok in function changes original string value as parameter
问题描述
当我使用strtok对一个c ++字符串进行标记化时,会发生一个混乱的问题,请看下面的简单代码:
when I use strtok to tokenize a c++ string, it happens a confusing problem, see the simple code below:
void a(string s){
strtok((char*)s.c_str(), " ");
}
int main(){
string s;
s = "world hello";
a(s);
cout<<s<<endl;
return 0;
}
程序输出world。
不应该输出world hello?因为我把字符串作为值参数传递给函数a,strtok不应该修改原来的...
任何人都可以解释这个伎俩。
问题是(char *)s.c_str()。
谢谢。
the program outputs "world". Shouldn't it output "world hello"? Because I pass the string as a value parameter to function a, the strtok shouldn't modify the original s... Can anyone explain this trick. thank you.
推荐答案
,你正在转换constness并修改 string
内容,你不应该这样做。虽然不应该修改原来的 s
,但我可能已经被一个智能优化,希望你玩的规则。例如, string
的COW实现将会显示该行为。
The problem is (char*)s.c_str()
, you are casting the constness away and modified the string
contents in a way that you are not supposed to. While the original s
should not be modified, I pressume you may have been hit by a smart optimization that expects you to play by the rules. For instance, a COW implementation of string
would happen to show that behavior.
这篇关于c ++ strtok在函数中将原始字符串值更改为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!