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++){
       for(j=0; (isdigit(str[j])!=0); j++){
          for(k=0; k<n; k++)
       for(j=0; j<n; j++)
  2. jcsd
  3. Mar 1, 2012 #2


    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


    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:

    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;
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook