1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Parsing str to int in C

  1. Feb 29, 2012 #1
    I need to take the values from a string , such as {23 45 67\0}, and store them into an int array. I need to do this with atoi() and isdigit() but I'm having some issues. Here is what I have.

    Code (Text):

    for(i=0; i<=n; i++){
       num[i]=atoi(str);
       for(j=0; (isdigit(str[j])!=0); j++){
          for(k=0; k<n; k++)
             str[k]=str[k+1];
             n-=1;
       }
       for(j=0; j<n; j++)
          str[k]=str[k+1];
       n-=1;
    }
     
  2. jcsd
  3. Mar 1, 2012 #2

    Borek

    User Avatar

    Staff: Mentor

    Have you tried to follow what your code does with a debugger? Watching how the variables change is the best way of understanding what is happening.

    I would not copy str content, instead, I would call atoi on a string starting at the place next number starts. Something like atoi(str+index_of_the_character_next_number_starts). I assume you know how pointers and tables work in C.
     
  4. Mar 1, 2012 #3
    I wasn't able to figure out how to track variables in a debugger. However, the due date was extended so I will sit down this weekend and try to figure it out. Also, I'll have another chance to talk to the prof tomorrow. We've not done anything with pointers so I'm not sure if that's an option or not; I'll ask. Thanks for the input.
     
  5. Mar 1, 2012 #4

    Mark44

    Staff: Mentor

    In C, a string is an array of type char. Are the numbers you show the ASCII codes of the characters in the string? For example, in the string "CAB" the actual values in memory are 67 65 66 0. If all you need to do is print the ASCII values of the characters, just loop through the string to get each character, but use printf to display it as an int.
     
  6. Mar 5, 2012 #5
    A string which contains "123" in memory would look like this:
    31h
    32h
    33h

    this because the the ASCII correspondents of numbers are 30h for 0 up to 39h for 9.

    so if the string has "asdasd" this cannot be converted to int using atoi(). The string should only contain characters with ASCII code varying from 30h to 39h.

    If you want to convert characters to int, then simply do this.


    if we have
    str (char array), num (int array), n = strlen(str) then do this
    for(int i=0;i<n;i++) {
    num = str;
    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Parsing str to int in C
  1. C++ . (Replies: 19)

  2. Parse tree (Replies: 3)

Loading...