C++ 将字符串作为参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8787243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing string as argument
提问by Roger
//EDITED: follow up question:
//编辑:跟进问题:
But making the function as isUnique(const char *s)
and then calling function as isUnique(str.c_str())
does not allow me to modify my string str
in the function
//
但是使函数 asisUnique(const char *s)
然后调用函数 asisUnique(str.c_str())
不允许我修改str
函数中的字符串
//
I am having problem with passing a string:
我在传递字符串时遇到问题:
bool isUnique(char *s)
{
int arr[256] = {0};
while(*s)
{
arr[*s]++;
if(arr[*s]>1)
{
cout<<"not unique";
return false;
}
}
}
int main()
{
string str = "abcda";
cout<<"1: True : unique, 2: False: Not Unique"<<endl<<isUnique(str);
}
ERROR:cannot convert 'std::string {aka std::basic_string}' to 'char*' for argument '1' to 'bool isUnique(char*)'
错误:无法将参数 '1' 的 'std::string {aka std::basic_string}' 转换为 'char*' 到 'bool isUnique(char*)'
回答by Nawaz
Pass the argument as:
将参数传递为:
isUnique(str.c_str());
And make the parameter type of the function asconst char*
:
并将函数的参数类型设为const char*
:
bool isUnique(const char *s)
Because std::string::c_str()
returns const char*
.
因为std::string::c_str()
返回const char*
。
Or even better, make the parameter const string&
:
或者甚至更好,使参数const string&
:
bool isUnique(const std::string & s);
And pass as you do : isUnique(str)
. Inside the function you can use s[i]
to access the characters in the string, where 0 <= i < s.size()
.
并像你一样通过:isUnique(str)
。在函数内部,您可以s[i]
用来访问字符串中的字符,其中 0 <= i < s.size()
.
回答by Fred Foo
Use
用
isUnique(str.c_str())
and make sure isUnique
takes a char const *
argument.
并确保isUnique
接受一个char const *
论点。
回答by Daniel Daranas
You are not passing a string. You are passing a char *
and trying to create one from a string
. Of course the conversion from string
to char *
is not automatic - they are two very different things.
您没有传递字符串。您正在传递 achar *
并尝试从 a 创建一个string
。当然,从string
to的转换char *
不是自动的——它们是两个非常不同的东西。
I suggest that you write this function:
我建议你写这个函数:
bool isUnique(const std::string& s)
回答by r_ahlskog
Either change function to accept
要么改变功能接受
bool isUnique(const string& s)
bool isUnique(const string& s)
and pass the string as a const reference
并将字符串作为常量引用传递
or do as the two other fine people suggested.
或者按照另外两个好人的建议去做。
This being C++ it would be preferable to pass a const std::string&
unless of course you have to be compatible with some C code or just have a requirement of using C-strings.
这是 C++,const std::string&
除非您必须与某些 C 代码兼容或只需要使用 C 字符串,否则最好传递 a 。