打印字符串的所有子串时出错
Error in printing all substrings of a string
这是参考 Synxis 的以下回答。
假设,我必须打印字符串 "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*)'
为什么会这样?
你用的是字符串,在函数中是char 尝试用char[] s;
在传递参数时在字符串 class 中使用 c_str() method
string s;
cin>>s;
findAllSubstrings2(s.c_str());
如错误消息所述,当您尝试传递类型为 std::string
的参数时,函数 findAllSubstrings2
的参数被声明为具有类型 const char *
string s;
//...
findAllSubstrings2(s);
您应该使用 class std::string
的成员函数 c_str
或 data
(从 C++ 11 开始)。例如
findAllSubstrings2(s.c_str());
您可能应该更改函数参数的类型。有些像:
void findAllSubstrings2(string s){
//... function implementation...
}
这是参考 Synxis 的以下回答。
假设,我必须打印字符串 "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*)'
为什么会这样?
你用的是字符串,在函数中是char 尝试用char[] s;
在传递参数时在字符串 class 中使用 c_str() method
string s;
cin>>s;
findAllSubstrings2(s.c_str());
如错误消息所述,当您尝试传递类型为 std::string
findAllSubstrings2
的参数被声明为具有类型 const char *
string s;
//...
findAllSubstrings2(s);
您应该使用 class std::string
的成员函数 c_str
或 data
(从 C++ 11 开始)。例如
findAllSubstrings2(s.c_str());
您可能应该更改函数参数的类型。有些像:
void findAllSubstrings2(string s){
//... function implementation...
}