0

I am learning C and I am trying to get a toy example working. My fake use case is given a string of chars where each char represents and int, loop over each char of the string and convert it to an int. What I've tried so far has not worked.

EDIT: Original question edited to now include a main() to allow responders to compile and using strtol per suggestions in comments.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {
  char *charNums = "12345";
  int num, num2, num3, i, n = strlen(charNums);
  char *ptr = charNums;

  for (i = 0; i < n; i++) {
    num = atoi(&charNums[i]);
    num2 = atoi(ptr);
    num3 = strtol(ptr, NULL, 10);
    printf("\ncharNums[%d] = %c (the expected value but as an int not a char)\n num = %d\n num2 = %d\n num3 = %d\n", 
        i, charNums[i], num, num2, num3);
    ptr++;
  }
  return 0;
)

Edit: Show method of compiling of C code along with program execution

gcc -o soQuestion main.c
./soQuestion
charNums[0] = 1 (the expected value but as an int not a char)
  num = 12345
  num2 = 12345
  num3 = 12345

charNums[1] = 2 (the expected value but as an int not a char)
  num = 2345
  num2 = 2345
  num3 = 2345

charNums[2] = 3 (the expected value but as an int not a char)
  num = 345
  num2 = 345
  num3 = 345

charNums[3] = 4 (the expected value but as an int not a char)
  num = 45
  num2 = 45
  num3 = 45

charNums[4] = 5 (the expected value but as an int not a char)
  num = 5
  num2 = 5
  num3 = 5

Appreciate any feedback.

Edit: The desired outcome of this program is to convert each char in the chars string "12345" to individual ints of 1 2 3 4 5 so I can do math with them such as sum them 1 + 2 + 3 + 4 + 5 = 15

SciGuyMcQ
  • 993
  • 6
  • 21
  • if you want just one character at a time, looping through the string and subtracting `'0'` from each character should work.. of course you'll have to verify your string is all base 10 characters first – yano Jan 17 '18 at 17:28
  • what exactly did not work out? – user2736738 Jan 17 '18 at 17:28
  • looks to me like its working fine – JoshKisb Jan 17 '18 at 17:28
  • 1
    the function: `strlen()` returns a `size_t` not an `int`, – user3629249 Jan 17 '18 at 17:32
  • the function: `atoi()` takes all the characters, starting at the indicated address, until it reaches a non-digit character, so the code is not going char by char but rather progressively dropping a leading digit. Also, the function `atoi()` (in general) should not be used as it gives no indication of success/failure. Suggest using: `strtol()` – user3629249 Jan 17 '18 at 17:36
  • @user3629249 I have made the `main()` explicit now so it should compile just fine :). Implicit type conversion seems to handle the size_t (or unsigned long) to int just fine for this toy example, thanks for pointing that out though ... I'm playing with `strtol` now but it appears to be doing the same thing. I'll post another edit soon. – SciGuyMcQ Jan 17 '18 at 17:47
  • also add your expected output – yano Jan 17 '18 at 17:49
  • implicit conversions are risky. Either cast to the desired type (which indicates your aware of the potential problems) or use the correct types – user3629249 Jan 17 '18 at 17:53
  • for ease of readability and understanding: 1) use meaningful variable names. variable names should indicate `content` or `usage` (or better, both) 2) follow the axiom: *only one statement per line and (at most) one variable declaration per statement.* 3) consistently indent the code. indent after every opening brace '{'. unindent before every closing brace '}'. Suggest each indent level be 4 spaces. – user3629249 Jan 17 '18 at 18:02
  • When editing a question, always indicate the changes (perhaps by using `EDIT:` ) Otherwise, such edits make prior comments meaningless and lending confusion to future readers of the question. – user3629249 Jan 17 '18 at 18:04
  • @user3629249 this is why people don't want to use this site anymore. Clearly I'm doing the following: explaining that I'm new to the language, using brevity (no `main` originally because it does not convey purpose of question), not concerned about type conversions because its a toy example not iron clad production code, Editing the original question with bold Edit tags and and explanation, do i need to go on ...? – SciGuyMcQ Jan 17 '18 at 18:08
  • regarding: `for ( i = 0; i < n; i++ )` Because each 'string' is terminated with a NUL byte ('\0') and because it is good programming practice to limit the scope of a variable, this statement could be modified to: `for ( int i = 0; charNums[i]; i++ )` – user3629249 Jan 17 '18 at 18:10
  • When asking a question about a runtime problem, as this question is doing, it is necessary to post a [mcve]. Questions that do not adhere to the giudelines tend to get marked down and soon closed. The original question failed to provide that key component. Suggest you read the help topic – user3629249 Jan 17 '18 at 18:12
  • when compiling, always enable the warnings, then fix those warnings. ( for `gcc`, at a minimum use: `-Wall -Wextra -Wconversion -pedantic -std=gnu11` ) – user3629249 Jan 17 '18 at 18:19
  • if you want to convert to individual ints from chars then subtract 48 from each char. I hope you know that ascii value of char '0' is 48, therefore int 0 can be obtained by '0' - 48 = 0. In my opinion, the problem is prettry simple and your program is too complex which is not required. – Nitin Jan 17 '18 at 18:26

3 Answers3

1

You can treat characters as number while doing the subtraction in this way:

int diff = c - '0';  //c is a character. 
//Avoid using hard code values like 48 in place of '0'.
//as they less readable.

then the diff is nothing, but the integral value.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
0

Hello My Friend i think you want to convert each char to an integer so here is the code if you requirement is same.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int my_atoi(char *str_to_int){

    int num = 0;
    for(int rot=0 ; str_to_int[rot] ; rot++){

            num = num * 10 + (str_to_int[rot] - 48);
            printf("Char to int is :: %d\n",num);
    }
    return num;
}


int main() {

    char *charNums = "12345";
    int get_int;

    get_int = my_atoi(charNums);
    printf("In String :: %s In Integer :: %d\n",charNums,get_int);
}

OutPut is:

Char to int is :: 1
Char to int is :: 12
Char to int is :: 123
Char to int is :: 1234
Char to int is :: 12345
In String :: 12345 In Integer :: 12345
cdhaval
  • 1
  • 2
0

The full and complete answer to my question is here. Thanks to @Saurav Sahu and @yano for leading me in the right direction.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  char *charNums = "12345";
  int num;

  for (int i = 0; charNums[i]; i++) {
    num = charNums[i] - '0';
    printf("\ncharNums[%d] = %c", i, charNums[i]);
    printf("\nnum = %d\n", num);
  }
  return 0;
}

Compiling and output of program.

➜  testcompile gcc -o soQuestion main.c
➜  testcompile ./soQuestion

charNums[0] = 1
num = 1

charNums[1] = 2num = 2

charNums[2] = 3
num = 3

charNums[3] = 4
num = 4

charNums[4] = 5
num = 5
SciGuyMcQ
  • 993
  • 6
  • 21