Converting String to Int in C: Issues with atoi() and isdigit() | Code Solution

  • Thread starter Thread starter TheSourceCode
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 4K views
TheSourceCode
Messages
14
Reaction score
0
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:
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;
}
 
Physics news on Phys.org
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.
 
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.
 
TheSourceCode said:
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.
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.
 
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;
}