繁体   English   中英

打印字符串的所有子字符串时出错

[英]Error in printing all substrings of a string

这是参考Synxis的以下答案。

https://codereview.stackexchange.com/questions/18684/find-all-substrings-interview-query-in-c/18715#18715

假设我必须打印字符串“ cbaa”的所有子字符串。 为此,我必须调用如下方法:

findAllSubstrings2("cbaa");

如果我从用户那里获取字符串,请执行以下操作:

string s;
cin>>s;
findAllSubstrings2(s);

它给出以下错误:

[Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'void findAllSubstrings2(const char*)'

为什么会这样?

如错误消息所述,当您尝试传递类型为std::string的参数时,函数findAllSubstrings2的参数声明为const char *类型。

string s;
//...
findAllSubstrings2(s);

您应该使用成员函数c_str或类std::string data (从C ++ 11开始)。 例如

findAllSubstrings2(s.c_str());

您使用字符串,在功能上是char尝试使用char [] s;

传递参数时在字符串类中使用c_str()方法

string s;
cin>>s;
findAllSubstrings2(s.c_str());

您可能应该更改函数参数的类型。 像这样:

void findAllSubstrings2(string s){
 //... function implementation...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM