Zining Zhu
Zining Zhu

Reputation: 323

"conversion to const char*" error when passing string to function

I tried to pass a string value to a function, but the DevC++5.6.1 reports an error (invalid conversion from char to const char*). Here is the program:

#include<iostream>
#include<string>
using namespace std;

string mysubstr(string target, int start_pos, string end_char) {
    for(int i = 0; i < target.size(); ++i)
        if(target[i] == ".") 
            return target.substr(0, i);
    return target;
}

int main() {
    string temp;
    cin >> temp; 
    string day0 = mysubstr(temp, 0, '.');
    return 0;
}

I wonder why this happens and how to fix it. Thank you. By the way: There is the same erro if the function head (5th line) is changed to

string mysubstr(const string &target, int start_pos, string end_char) {

Edit: The function should be the following. Two modifications to the original one: (1) The caller should use double quote; (2) in comparison I should use target.substr(i, 0). (3) The two parameters start_pos and end_char are used now.

string mysubstr(string target, int start_pos, string end_char) {
    for(int i = 0; i < target.size(); ++i)
        if(target.substr(i, 1) == end_char) 
            return target.substr(0, i);
    return target;
}

Upvotes: 0

Views: 484

Answers (3)

Arthur Laks
Arthur Laks

Reputation: 514

The last parameter to your function is a string, but when you call it, you are passing it a char instead. You can solve the problem by putting that argument in double-quotes instead of single quotes, because char arrays are implicitly converted to strings.

Upvotes: 1

David G
David G

Reputation: 96845

You're passing a character '.' to a parameter of type const char*. The types don't match which is your problem. You probably want to use a string literal:

string day0 = mysubstr(temp, 0, ".");
//                              ^ ^

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49921

You are comparing a character with a string (target[i] == ".") and passing a character to a string parameter ('.' for end_char). Note that you don't actually use end_char in your function, nor start_pos for that matter.

Upvotes: 2

Related Questions