Search code examples
c++castingconst-char

How do I convert a String into a char in C++


I want to convert a string that is inside a vector of strings (vector) into a char. The vector would look something like the following: lons = ["41", "23", "N", "2", "11" ,"E"]. I would like to extract the "N" and the "E" to convert them into a char. I have done the following:

char lon_dir;
lon_dir = (char)lons[lons.size()-1].c_str();

But I get the following error message:

cast from 'const char*' to 'char' loses precision [-fpermissive]

How do I fix that?


Solution

  • You cannot directly cast a c string (char* or const char*) to a char as it is a pointer. More precisely a pointer to an array of chars!

    So once you retrieve the right char* (or const char*) from your array lons it suffices to dereference said pointer, this will return the first character of that string

    char* str = "abc";
    char a = *str;
    char b = *(str + 1);
    

    etc...