Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.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:字符串,例如“字符串”;abcde123“;到int 123_C_String_Function_Int_Type Conversion - Fatal编程技术网

C:字符串,例如“字符串”;abcde123“;到int 123

C:字符串,例如“字符串”;abcde123“;到int 123,c,string,function,int,type-conversion,C,String,Function,Int,Type Conversion,我的问题很简单。如果在实际整数之前有任意数量的冗余字符,C中是否有将字符串转换为int的函数 可指定该问题涵盖两种情况: 1) 在整数前面加空格的字符串:“abcde 123” 2) 在整数前面带有任何非数字字符的字符串:“abcde:123”可以使用scanf函数系列来执行此操作。因此,我将首先演示,然后解释: int x; scanf("%*[^0123456789+-]%d", &x); 第一个格式说明符是[]。它指定scanf应接受的字符族。前导的^否定了这一点,因此说明符接受

我的问题很简单。如果在实际整数之前有任意数量的冗余字符,C中是否有将字符串转换为int的函数

可指定该问题涵盖两种情况: 1) 在整数前面加空格的字符串:“abcde 123”
2) 在整数前面带有任何非数字字符的字符串:“abcde:123”

可以使用
scanf
函数系列来执行此操作。因此,我将首先演示,然后解释:

int x;
scanf("%*[^0123456789+-]%d", &x);

第一个格式说明符是
[]
。它指定
scanf
应接受的字符族。前导的
^
否定了这一点,因此说明符接受该族以外的任何内容。最后,
*
用于抑制实际输入,因此在扫描输入流以查找模式时,不会尝试将其分配到任何内容。

您可以使用
isalpha
isdigit
from
ctype.h
查找第一个数字,然后使用
atoi
atol
atol
strol
walk
转换为
int
,例如:

#include <ctype.h>
#include <stdlib.h>

int main(void) {
  char str[] = "abcde123";

  char *p = str;
  while (isalpha(*p)) ++p;
  int i = atoi(p);
}
#包括
#包括
内部主(空){
char str[]=“abcde123”;
char*p=str;
而(isalpha(*p))++p;
int i=atoi(p);
}

请注意,“如果转换后的值[的
atoi
/
atol
/
atol
]超出相应返回类型的范围,则返回值未定义。”()。

您可以使用
sscanf()
或使用
strtoll()

23
123


基本上,整数在字符串中的位置无关紧要,它将提取所有整数。

使用
strspn()
查找第一个数字字符,然后使用
atoi
sscanf
解析从那里开始的数字。函数scanf是不安全的。如果字符串不能在类型中表示,则会得到未定义的行为。函数atoi是不安全的。如果字符串不能在类型中表示,您将获得未定义的行为。这是一个优雅的解决方案。我想我们也可以避免包含ctype,如果atoi无法转换,甚至可以利用它返回0。在我的例子中,您会看到数字不会以0开头,因为它们被转换为正整数。干杯@2501这是不正确的。如果不能进行转换,函数返回零。@Fredrik不要歪曲我的话。我从来没有说过如果不能进行转换,行为是未定义的。我只是说,如果值无法表示,即使用的输入值较大,则行为未定义。这是正确的,我引用:如果结果的值无法表示,则行为是未定义的。@Fredrik旁注:由于您声称atoi返回零,请引用标准中指定此值的部分。我认为你在这里实际上是错的,因为对于atoi没有这样的规则。
sscanf
在评论方面并不比
scanf
更安全。你有点误解了那句话的意思。我不认为
strtol()
strtoll()更安全。如果值超出可表示的范围,则设置
errno
。@DavidBowling是,但
atol
atoi
不是。谢谢你的更正
//char string1[] = "abcde:123";
    char string[] = "ab23cde:123";
    int values[4]; // specify the number of integers expected to be extracted
    int i = 0;
    char *pend = string;
    while (*pend) {
        if (isnumber(*pend)) {
            values[i++] = (int) strtoll(pend, &pend, 10);
        } else {
            pend++;
        }
    }

//you can use a forloop to go through the values if more integers are expected

        printf("%d \n",values[0]);
        printf("%d \n",values[1]);