Go Down

Topic: problem in reading String and performing Mathematical operations.... (Read 425 times) previous topic - next topic

ManasviSihag

i want to add the values inside a,b,c and then want to print them on serial port.But the Serial.println command is printing the Decimal value of the addition( sum=a+b+c )that is 150 but i want output should be 6.Need Help Please Reply...Thanks
My Code is:-


Code: [Select]
[code][code]

int a,b,c,sum;
void setup()
{
Serial.begin(9600);
}

void loop()
{
 
String reportString = "1$123$$456$$$789";
int spacePosition0 = reportString.indexOf('1');
int spacePosition1 = reportString.indexOf('$');
a=(int)reportString.charAt(spacePosition1 + 1);
b=(int)reportString.charAt(spacePosition1 + 2);
c=(int)reportString.charAt(spacePosition1 + 3);

if (reportString.charAt(spacePosition0) == '1')
{
    sum=a+b+c;
    Serial.println(sum);
    delay(1000);
}
}
[/code][/code]

AWOL

The calculation is correct - you're adding the ASCII values of the characters.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

ManasviSihag

@AWOL
i want Serial.Println(sum); to print 6 as the sum of a=1,b=2,c=3.But the command is printing 150 by adding the Decimal Values of a,b and c (49,50 and 51) respectively.So AWOL how can i get this value.......please help.

AWOL

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

ManasviSihag


Nick Gammon

Please note that, at present, the String library has bugs as discussed here and here.

In particular, the dynamic memory allocation used by the String class may fail and cause random crashes.

I recommend reworking your code to manage without String. Use C-style strings instead (strcpy, strcat, strcmp, etc.).
http://www.gammon.com.au/electronics

Go Up