简体   繁体   中英

“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;
}

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.

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, ".");
//                              ^ ^

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM