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

Error in printing all substrings of a string

本文关键字:字符串 出错 打印      更新时间:2023-10-16

这是参照Synxis的以下回答。

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

假设,我必须打印字符串"cbaa"的所有子字符串。要做到这一点,我必须像这样调用方法:

findAllSubstrings2("cbaa");

如果我从user获取一个字符串,并执行以下操作:

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);

应该使用std::string类的成员函数c_strdata(从c++ 11开始)。例如

findAllSubstrings2(s.c_str());

您使用的是字符串,在函数是char尝试使用char[] s;

在传递参数

时在string类中使用c_str()方法
string s;
cin>>s;
findAllSubstrings2(s.c_str());

您可能应该更改函数的参数类型。Somethink:

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