user18559097
user18559097

Reputation:

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?

Upvotes: 1

Views: 387

Answers (1)

Plegeus
Plegeus

Reputation: 260

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...

Upvotes: 5

Related Questions