Go Down

Topic: sprintf() function (Read 972 times) previous topic - next topic

Xenon69

Someone can help with sprintf(); ?
I need seperate numbers and asign them to Variables.

Code: [Select]
int number = 123456;

void setup()
{
  Serial.begin(9600);
}

void loop()
{
int buff[5];
sprintf(buff, "%.6u", testNumber);
int Variable[5];
Variable1 = buff[0];
Variable2 = buff[1];
Variable3 = buff[2];
Variable4 = buff[3];
Variable5 = buff[4];
Variable6 = buff[5];

Serial.println(Variable);
}


Can someone repair my code?

majenko

1. What are Variable1 to Variable6?
2. You can't use a decimal formatting on an unsigned integer.
Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

Xenon69

Variable can be integer

Actualy it is does not matter, I just would like that this code was work.

majenko


Variable can be integer

Actualy it is does not matter, I just would like that this code was work.


Variable is an integer array.

Variable1, Variable2, Variable3, Variable4, Variable5 and Variable6 are undefined.

I think you meant to use Variable[0] through Variable[5] instead.
Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

PaulS

You can't write 6 characters and a terminating NULL in a 5 element array.

majenko

... The whole program is just one big error from start to finish...
Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

guix

#6
Mar 10, 2013, 09:04 pm Last Edit: Mar 10, 2013, 09:09 pm by guix Reason: 1
Hello, let me link you to a similar topic: http://arduino.cc/forum/index.php?topic=132940.0 :)

But still, your idea of using sprintf could work, if you understand that an array of size 5 can hold 5 elements: 0, 1, 2, 3, 4. And, as said, the string must have enough room for (in your case) 7 characters: '1', '2', '3', '4', '5', '6', '\0'.

kowalski

Another suggestion is just to simply map from character to integer. So the fix to your code is:

Code: [Select]
Variable[0] = buff[0] - '0';

Cheers!

PaulS

Quote
So the fix to your code is:

That will work for '0' to '9', but fail rather miserably for 'A' to 'F'.

kowalski


Quote
So the fix to your code is:

That will work for '0' to '9', but fail rather miserably for 'A' to 'F'.

True but using sprintf(buff, "%.6u", testNumber) should not include them? And yepp I know this is another problem with original code. After fixing the number format for sprintf we will need to get back to how to map character '0'..'9' and 'A'..'F' to number 0..15.

Small steps forward!


Go Up