String manipulation using Arduino and C++


Question

I am trying to manipulate a string in C++. I am working with an Arduino board so I am limited on what I can use. I am also still learning C++ (Sorry for any stupid questions)

Here is what I need to do: I need to send miles per hour to a 7 segment display. So if I have a number such as 17.812345, I need to display 17.8 to the 7 segment display. What seems to be most efficient way is to first multiply by 10 (This is to shift the decimal point right one place), then cast 178.12345 to an int (to chop decimal points off). The part I am stuck on is how to break apart 178. In Python I could slice the string, but I can't find anything on how to do this in C++ (or at least, I can't find the right terms to search for)

There are four 7 segment displays and a 7 segment display controller. It will measure up to tenths of a mile per hour. Thank you very much for an assistance and information you can provide me.

1
3
5/1/2016 7:23:04 AM

It would probably be easiest to not convert it to a string, but just use arithmetic to separate the digits, i.e.

float speed = 17.812345;
int display_speed = speed * 10 + 0.5;     // round to nearest 0.1 == 178
int digits[4];
digits[3] = display_speed % 10;           // == 8
digits[2] = (display_speed / 10) % 10;    // == 7
digits[1] = (display_speed / 100) % 10;   // == 1
digits[0] = (display_speed / 1000) % 10;  // == 0

and, as pointed out in the comments, if you need the ASCII value for each digit:

char ascii_digits[4];
ascii_digits[0] = digits[0] + '0';
ascii_digits[1] = digits[1] + '0';
ascii_digits[2] = digits[2] + '0';
ascii_digits[3] = digits[3] + '0';
10
12/5/2009 7:12:45 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon