C程序:将表示数字的字符串转换为整数

时间:2018-01-17 17:26:11

标签: c string char int

我正在学习C,我正试图让一个玩具示例工作。我的假用例给出了一串字符,其中每个char表示和int,循环遍历字符串的每个字符串并将其转换为int。到目前为止我所尝试的并没有奏效。

编辑:现在编辑的原始问题包括main(),以便响应者根据评论中的建议编译和使用strtol

#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;
)

编辑:显示编译C代码的方法以及程序执行

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

感谢任何反馈。

编辑:此程序的预期结果是转换字符串中的每个字符串&#34; 12345&#34;单个整数1 2 3 4 5所以我可以用它们做数学,如求和1 + 2 + 3 + 4 + 5 = 15

3 个答案:

答案 0 :(得分:1)

您可以通过以下方式处理subtraction时将字符视为数字:

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

然后diff不算什么,而是整数值。

答案 1 :(得分:0)

Hello My Friend我想你想把每个char转换成一个整数,所以如果你的要求是相同的话,这里是代码。

#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是:

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

答案 2 :(得分:0)

我的问题的完整和完整答案就在这里。感谢@Saurav Sahu和@yano带领我朝着正确的方向前进。

#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;
}

编制和输出节目。

➜  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