1

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?

Wyck
  • 10,311
  • 6
  • 39
  • 60
Nhenon
  • 49
  • 7
  • What if there are multiple characters? – lorro Oct 03 '22 at 15:35
  • 3
    `std::string` supports indexing, so no need to use `c_str()` and such. `std::string s = "N"; char n = str[0];` or `char n = str.at(0);` to provide range checking and throw an exception on out of bounds access. Always check the `size()` or `length()` or the string before using `[index]`. – Retired Ninja Oct 03 '22 at 15:40
  • If you have `std::string str = lons[lons.size()-1];` then `str[0]` is the first character of that string. or just `lons[lons.size()-1][0]` all in one expression. – Wyck Oct 03 '22 at 15:40
  • You can't convert a `string` to a single `char`. A char holds one letter or symbol. A string contains zero or more letters or symbols. You can't squeeze more than one letter into a single character without loss of data. – Thomas Matthews Oct 03 '22 at 15:45
  • @AviBerger I figured you were just using what was in the question, which is kinda awkward even if it works. :) I often wonder why I don't use `front()` and `back()` more often since I like to show intent as much as possible. *shrug* `string` gives you far too many ways to do things sometimes. `s.data()[0]`? – Retired Ninja Oct 03 '22 at 16:07

1 Answers1

5

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

Plegeus
  • 139
  • 11
  • Thank you! I solved it by gettin the first element of the string like so: string[0] – Nhenon Oct 03 '22 at 16:27
  • Great! Can you please mark the answer as solved? Then I get points! :) Also, I forgot to mention: *str and str[0] are the same... – Plegeus Oct 03 '22 at 19:33
  • I see that you removed `const` from `const char* str = "abc";` which makes the code you are showing invalid. I would rollback to edit 2 which I made to make it valid. – Ted Lyngmo Oct 04 '22 at 21:02
  • Don't worry, this piece of code won't make into production. As I mentioned in the edit, the essence is getting a char out of the string, how to handle strings in C is another story for another day. N.B. the code was tested and runs on windows. – Plegeus Oct 06 '22 at 07:01