1

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

forest.peterson
  • 755
  • 2
  • 13
  • 30

4 Answers4

4

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.

Community
  • 1
  • 1
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

A char is not a string.

A char is also not a null-terminated string.

A null-terminated string is a char array with the null character at the end.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • so I could have done something like `char a; string a_test = 'a' + '\n'` – forest.peterson Mar 06 '13 at 00:55
  • 1
    @forest No, since adding two `char`s doesn’t concatenate them, it adds their byte value. But you can concatenate an (empty) string and a `char`: `string() + 'a'` works (but is probably less efficient than my code). Note that `"" + 'a'` does *not* work, since `""` is *not* a string, it’s a null-terminated `char` array. – Konrad Rudolph Mar 06 '13 at 09:47
0

Replace (string)a with string(1,a)

Happy Green Kid Naps
  • 1,611
  • 11
  • 18
0

Everything already mentioned works, but you may also want to try:

char mychar = 'A';
string single_char = "";
string += mychar;

Hope that helps!

Ibrahim
  • 798
  • 6
  • 26