Search code examples
c++stringcastingchar

(string)char typecast


I want to cast a char to a string with this function:

int charIndexDistance (char a, char b)
{
    if (indexical) {
        string test_a = convertOntology((string)a, 0);
        string test_b = convertOntology((string)b, 0);
        cout << test_a << " " << test_b << endl;

        int test = abs(char_index[a] - char_index[b]);
        return test; //measure indexical distance between chars
    } else 
        return 1;
}

but I get this "error C2440: 'type cast' : cannot convert from 'char' to 'std::string"

what is thr problem? and how is a char cast to a string - should I use string append?

also, the cout and int test are for debugging purposes and will be removed later


Solution

  • There simply is no such conversion. Instead, you have to construct a string manually:

    string(1, a)
    

    This uses the constructor taking a length and a char to fill the string with.

    In the context of your code:

    string test_a = convertOntology(string(1, a), 0);
    string test_b = convertOntology(string(1, b), 0);
    

    Even if an appropriate constructor / cast existed your code would be bad since you should avoid C-style casts in C++. The situation would call for a static_cast instead.