-2

I have a code where I read a text file into a string. The string is called "line". Now I take the first element of line "line[0]" which is 3, and the second element of line "line[1]" which is 8. I want to combine them into an array called ary[0].

What I did was ary[0] = line[0] + line[1] and expected to get "38", but instead, I got "107".

Why doesn't line[0] + line[1] work? What is the proper way of combining the two elements? I tried strcat(line[0],line[1]) but I get an error: invalid conversion from ‘char’ to ‘char*’.

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
BadProgrammer
  • 89
  • 1
  • 2
  • 12

1 Answers1

0

The first element is '3' (ASCII character for number 3), not 3 (numeric value). You need to convert the ASCII character to numeric value and also, you cannot just add them to get the value, you need to calculate with them as with numbers, ie. multiply the first by 10 to get 30:

ary[0] = (line[0] - '0') * 10 + (line[1] - '0');

Or, if you want to keep them as strings, you need to define ary as vector of std::strings and use substr:

ary[0] = line.substr(0, 2);

(Note: originally I suggested using line[0] + line[1] but that does not work because that would again count with them as with numbers.)

StenSoft
  • 9,369
  • 25
  • 30
  • Ahhh that makes sense! Thank you! How does this apply if I am working with HEX? for example, line[0] = 6 and line[1] = F. How do I make ary[0] = 6F? – BadProgrammer Feb 13 '15 at 23:33
  • You would need to use [the right conversion](http://stackoverflow.com/a/1070499/4538344). (Also note that since ary[0] is a number, it would be decimal 111.) – StenSoft Feb 13 '15 at 23:38