简体   繁体   中英

C++ error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]

#include <iostream>
#include <string>
using namespace std;
float findSimilarityScore(string A, string B)
{
    string C;
    if (A.length() != B.length())
    {
        return -1;
    }
    if (A.length() == 0 and B.length() == 0)
    {
       return -1;
    }
    else
    {
        int i;
        for (i = 0; A.length() - 1; i = i+1)
        {
            if (A[i] == B[i])
            {
                C.append(A[i]);
            }
            if (A[i] != B[i])
            {
                return 0;
            }

        }
    cout << C << endl;
    }
}

int main()
{
    findSimilarityScore("DDS","DAS");
}

when i try to run my code, my IDE show this:

/home/ubuntu/workspace/hmwk4/hmwk4-1.cpp: In function ‘float findSimilarityScore(std::string, std::string)’:
/home/ubuntu/workspace/hmwk4/hmwk4-1.cpp:24:30: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]

Why? I want : if the first char in A is same to the first char in B, then add this char to the string C. if the second char in A is same to the second char in B, then add this char to the string C. And so on.

In the line

C.append(A[i]);

std::string::append has no overload that takes a single char . Use push_back instead:

C.push_back(A[i]);

This will fix your compilation error, but your function is still logically incorrect. It returns 0 the first time it finds any character that doesn't match between the two strings, and if the two strings are identical then it will invoke undefined behavior by reaching the end of a non-void function without returning a value.

string::append() with a single parameter is expecting a string argument, you are passing a single char . Try

C.append(1, A[i]);

Also, once you find a non-matching char, you return without printing the new string. Move the cout just before the return

if (A[i] != B[i])
{
    cout << C << endl;
    return 0;
}

And be sure to add a return at the end of your function in case you don't find any characters which are unequal.

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