Error in printing all substrings of a string

79 views Asked by At

This is in reference to the following answer by Synxis.

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

Suppose, I have to print all substrings of the string "cbaa". To do this, I have to invoke the method like this:

findAllSubstrings2("cbaa");

If I take a string from user, and do the following:

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

it gives the following error:

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

Why does this happen?

4

There are 4 answers

2
Vlad from Moscow On BEST ANSWER

As the error message says the parameter of function findAllSubstrings2 is declared as having type const char * while you are trying to pass an argument of type std::string

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

You should use member function c_str or data (starting from C++ 11) of class std::string. For example

findAllSubstrings2(s.c_str());
2
Bogdan Tkachenko On

you using string, in function is char try to use char[] s;

0
Sajith Eshan On

use c_str() method in string class when passing the argument

string s;
cin>>s;
findAllSubstrings2(s.c_str());
0
Gardax On

You probably should change the type of the parameter of the function. Somethink like:

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