Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 给定一个字符数组,如何从该数组中提取多个数字并将其分配给int值?_C_Arrays_Character_Strtol - Fatal编程技术网

C 给定一个字符数组,如何从该数组中提取多个数字并将其分配给int值?

C 给定一个字符数组,如何从该数组中提取多个数字并将其分配给int值?,c,arrays,character,strtol,C,Arrays,Character,Strtol,假设我有一个字符数组 char *array = "hello my name is steven 123*3"; 我想从这个表达式中提取123,并把它放在一个int中 我知道我可以做像这样的事情 int firstnum = array[15] - '0'; 假设1是数组中的第15个字符,这将给我firstnum=1 但是我想把123的整数变成一个整数,我不知道怎么做 谢谢你的帮助 编辑:我刚刚发现了一种叫做strtol的东西,但我不确定如何使用它 我在想 long numberwante

假设我有一个字符数组

char *array = "hello my name is steven 123*3";
我想从这个表达式中提取123,并把它放在一个int中

我知道我可以做像这样的事情

int firstnum = array[15] - '0';
假设1是数组中的第15个字符,这将给我firstnum=1

但是我想把123的整数变成一个整数,我不知道怎么做

谢谢你的帮助

编辑:我刚刚发现了一种叫做strtol的东西,但我不确定如何使用它

我在想 long numberwanted=strtolarray[15],*p,10; 但我如何让它知道何时停止?或者当你到达一个非整型或非长型时,它会停止吗?什么是*p?

尝试使用sscanf

这假定前缀字符串永远不包含数字。 如果它可能包含一个数字,您可以从后面像这样读取它,假设数据由以下部分组成:前缀字符串、一个或多个数字、一个字符、一个或多个数字

  int n1 = 0, n2 = 0;
  char ch = 0;

  char *array = "hello my name is steven 123*3";
  size_t i = strlen(array);

  while (--i >= 0 && isdigit(array[i]))
    ;
  sscanf(array+i+1, "%d", &n2);

  ch = array[i];

  while (--i >= 0 && isdigit(array[i]))
    ;
  sscanf(array+i+1, "%d", &n1);

我有点困惑,我的号码到底存储在哪里?我希望能够对后面的数字进行计算,strtol或sscanf更适合吗?在上述任何一个代码段中,字符串末尾的第一个数字是n1,第二个数字是n2。假设它们由单个字符分隔,该字符被读取并存储在ch数组[15]中。15是错误的位置。斯特拉雷[15],*p,10;:数组[15]是char,而不是char*。
  int n1 = 0, n2 = 0;
  char ch = 0;

  char *array = "hello my name is steven 123*3";
  size_t i = strlen(array);

  while (--i >= 0 && isdigit(array[i]))
    ;
  sscanf(array+i+1, "%d", &n2);

  ch = array[i];

  while (--i >= 0 && isdigit(array[i]))
    ;
  sscanf(array+i+1, "%d", &n1);
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    char *array = "hello my name is steven 123*3";
    int num;
    char *p;//p in strtol : Pointer of position where a character that can not be interpreted appeared. point to '*' after execution.
    num = strtol(array + strcspn(array, "0123456789"), &p, 10);

    printf("%d\n", num);

    return 0;
}