Go Down

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

#### ManasviSihag

##### Nov 11, 2012, 12:20 am
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

#1
##### Nov 11, 2012, 12:25 am
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.
I speak for myself, not Arduino.

#### ManasviSihag

#2
##### Nov 11, 2012, 12:32 am
@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

#3
##### Nov 11, 2012, 12:35 am
Subtract '0' from each item before summing them.
"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.
I speak for myself, not Arduino.

#### ManasviSihag

#4
##### Nov 11, 2012, 12:45 am
Thanks AWOL.It was a great help from Your side.

#### nickgammon

#5
##### Nov 11, 2012, 05:38 am
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.).
Please post technical questions on the forum, not by personal message. Thanks!