Hi,
I am new to all this so please bear with me. My problem is that I need to turn a variable into a string with three digits.
e.g. I have a variable int called runs, which I need to convert to a string in order to output but it must be three digits long.
So my code is like this.
int runs ;
String stringRuns = String(runs);
This works fine if the value of runs is 100 - 999, however if the value is 10 - 99 the string will be 2 digits long, if less than 10 only 1 digit long.
How can I force the string to include the leading zeroes?
mwtheplumber:
How can I force the string to include the leading zeroes?
use C style strings instead, along with sprintf/snprintf:
int runs = 99;
char string[4];
snprintf(string, "%03d", runs); // Google: C++ format specifier
Serial.println(string);
which I need to convert to a string in order to output
As a matter of interest where is the output going to ?
The output is converted to a HEX string that goes to elctro-mechanical 7 digits displays via RS485
mwtheplumber:
...converted to a HEX string...
char string[5];
int data = 1010;
snprintf(string, sizeof(string), "%04X", data);
Serial.println(string);
Thanks for your help.
I have now progressed to putting three variables into 1 string which I can feed into the code to create the HEX string that will operate the numbers.
Code below which I have used to prove the concept.
void setup() {
// put your setup code here, to run once:
Serial.begin(19200);
}
void loop() {
// put your main code here, to run repeatedly:
int runs = 199;
int wkts = 3;
int overs = 24;
char cruns [4];
sprintf(cruns, "%03d", runs);
char cwkts [4];
sprintf(cwkts, "%03d", wkts);
char covers [4];
sprintf(covers, "%03d", overs);
Serial.println(cruns);
Serial.println(cwkts);
Serial.println(covers);
String StringRuns = String(cruns);
String StringWkts = String(cwkts);
String StringOvers = String(covers);
String Output = String (StringRuns+StringWkts+StringOvers);
Serial.print ("The runs are ");
Serial.println(StringRuns);
Serial.print ("The wkts are ");
Serial.println(StringWkts);
Serial.print ("The overs are ");
Serial.println(StringOvers);
Serial.println(Output);
delay(1000);
}
Do you really need to convert the strings to Strings ?