我的问题很简单。如果在实际整数之前存在任意数量的冗余字符,则C中是否有函数将字符串转换为int?
这个问题可以指定为两种情况: 1)在整数之前有空格的字符串:"abcde 123“2)在整数之前带有任何非数字字符的字符串:"abcde:123”。
发布于 2017-02-17 20:31:55
您可以使用isalpha或来自ctype.h的isdigit查找第一个数字,然后使用atoi或atol或atoll或strol或stroll转换为int,例如:
#include <ctype.h>
#include <stdlib.h>
int main(void) {
char str[] = "abcde123";
char *p = str;
while (isalpha(*p)) ++p;
int i = atoi(p);
}注意,“如果atoi / atol / atoll的转换值超出了相应的返回类型的范围,则返回值未定义。”(来源)。
发布于 2017-02-17 20:24:42
可以使用scanf函数系列来完成这一任务。我先演示一下,然后再解释:
int x;
scanf("%*[^0123456789+-]%d", &x);第一个格式说明符是[]。它指定了scanf应该接受的一系列字符。领先的^否定了这一点,所以除了该家族以外的任何东西都会被接受为说明符。最后,使用*来抑制实际输入,因此在扫描输入流以寻找模式时,不会尝试将其分配到任何东西中。
发布于 2017-02-17 20:56:34
可以使用sscanf(),也可以使用strtoll()。
//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]);23 123
基本上,无论整数在字符串中的位置如何,它都会提取所有的整数。
https://stackoverflow.com/questions/42306696
复制相似问题