Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Conversion from char to int?

  1. Mar 23, 2010 #1
    What could be wrong with this code?:

    Code (Text):


    int arr[10];
    char arr2[10];
    for (int i=0; i<10; i++)
    {
            arr[i]=(int)arr2[i];
    }

     
    When I output the supposedly converted array, it's outputs some crazy numbers.
    ???
     
  2. jcsd
  3. Mar 23, 2010 #2

    Filip Larsen

    User Avatar
    Gold Member

    I assume you are using C/C++ here, in which case you should note that automatic variables (variables defined on the stack) are not initialized. Try initialize your character array with some sensible values.
     
  4. Mar 23, 2010 #3
    It's arr2[10]="P 1 (a tab) 0";
     
  5. Mar 23, 2010 #4
    And it outputs: 80 49 9 48 0 0 0 0 0 0

    I want to get 1 and 0 as integers
     
  6. Mar 23, 2010 #5

    Filip Larsen

    User Avatar
    Gold Member

    Characters are internally represented by a byte that contains the code for the character in question. See for instance http://en.wikipedia.org/wiki/ASCII.

    To get the digit of the character you would normally first test if the character is in the range '0' to '9' and then subtract '0'. Something like this:

    Code (Text):

    char ch = ...;
    if (ch >= '0' && ch <= '9') {
      int digit = ch - '0';
      // do whatever you need with digit
    }
     
    Alternatively you can use some of the methods from the standard ctype.h library (see for instance http://www.cplusplus.com/reference/clibrary/cctype/).
     
  7. Mar 23, 2010 #6

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    80 = 'P'
    49 = '1'
    9 = tab
    48 = '0'
    0 = end of string

    It is working exactly right, assuming you are working on an ASCII machine.

    Then you want to do something other than a simple cast.
     
  8. Mar 23, 2010 #7
    Alright. The problem is solved to some extend. But a little more problem:

    For the given string [P 1 (tab) 0] it outputs fine: 1 0
    But when I have a string [P 2 (tab) 34] it outputs: 2 3 (no four.)

    What could be the problem?
     
  9. Mar 23, 2010 #8

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    You need to learn how to parse. Casting is not what you want here.
     
  10. Mar 23, 2010 #9

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    To add to the above:

    In this case, the function sscanf() will do the trick.

    For more complicated parsing problems, you will probably need to learn how to use things like strtok() to split the string into tokens and things like strtol() to convert the numeric tokens into integers.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook