Passing a string into a function as argument

Why can't I pass the string str to the function?
What will be the correction?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

bool magic (char *str1, char *search);


int main ()
{
    string str;

    getline(cin, str);

    if (magic(str, "1001"))   //Problem is here
        cout<<"MAGIC"<<endl;
    else
        cout<<"NORMAL"<<endl;

    return 0;
}



bool magic (char *str1, char *search)
{
    for (int i = 0; i < strlen(str1); ++i)
    {
        if (strncmp (&str1[i], search, strlen(search)) == 0)

            return true;
    }

    return false;
}
What does your compiler say about that line?

Perhaps:
In function 'int main()': 16:26: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'char*' for argument '1' to 'bool magic(char*, char*)'

The str is a std::string
Function parameter must have type char*

std::string has member c_str() that returns a const char*
that would not work either, because the magic() reserves the option to modify its parameter.

If string would modification of its content like that, then you could bypass the encapsulation and render the string inconsistent and invalid.
Last edited on
You're intermixing C-strings and C++ std::string. You've declared that magic takes two C-strings, but you're attempting to pass a std::string.

Are you coding in C or C++? Make a decision.

Also, why do you have a for loop at line 28? strcmp will compare 2 C-strings even if they are different lengths.

If you decide to use C++ std:string, you can get rid of the magic function all together. Line 16 becomes:
 
  if (str == "1001")

Topic archived. No new replies allowed.