将值从字符串转换为 int

Converting value from a string into an int

我在发帖前已经阅读了这个问题(Convert a string into an int),但我仍然有疑问。

我是 C 的新手,我正在尝试编写一个将字符串作为参数的函数,如下所示:

然后 returns 第一个将它找到的数字转换成一个整数。所以结果将是:

我试图通过查找字符串中的字符(对应于 ASCII table 中的数字)然后将它们存储在我创建并由函数返回的 int 中来实现。

我遇到了麻烦,因为当我找到那些字符(对应于数字)时,我不知道如何将它们保存到 int 数据类型变量或如何转换它们。我知道有一个名为 atoi 的函数可以自动执行此操作,但我想知道如何自己执行此操作。

这是我到目前为止写的:

int ReturnInt(char *str)
{
    int     i;
    int     new;

    i = 0;
    new = 0;
    while (str[i] != '[=10=]')
    {
         if( str[i] >= '0' && str[i] <= '9')
        {
            str[i] = new - '0';
        }
        i++;
    }

    return (new);
}

我认为你应该能够通过将数字乘以 10 并在迭代时添加它们来从数字中形成所需的整数。此外,我认为你的循环的终止条件还应该包括 isDigit check

例如,对于输入 99Hello

i = 0, new = 0 -> new = 0 * 10 + 9 (9)

i = 1,新 = 9 -> new = 9 * 10 + 9 (99)

i = 2,条件不满足,因为它不是数字

int ReturnInt(char str[]) {
  int i;
  int new;

  i = 0;
  new = 0;
  while (str[i] != '[=10=]' && (str[i] >= '0' && str[i] <= '9'))
    {
      int currentDigit = str[i] - '0';
      new = new * 10 + currentDigit;
      i++;
    }

  return (new);
}

您只需取一个占位符,每次迭代都必须将其乘以 10,以便我们得到 10、100、1000 个占位符,然后我们可以将该数量加到剩余的数字中。

#include <stdio.h>
#include <ctype.h>

int str2num(char*strnum);

int main()
{
    char *num1 = "122AB";
    char *num2 = "2345AB9C";
    char *num3 = "A23AB9C";
    
    printf("num1 = %d\n", str2num(num1));
    putchar('\n');
    printf("num2 = %d\n", str2num(num2));
    putchar('\n');
    printf("num3 = %d\n", str2num(num3));
    
    return 0;
}

int str2num(char*strnum)
{
    int num = 0;
    int ph = 10;// for getting tens,100s etc 
    
    while(strnum && *strnum && isdigit(*strnum))
    {

num = num * ph + ( (*strnum) - '0'); strnum++;

    }
    return num;
}