我有一个字符串(char),想从中提取数字。
所以,我有一个字符串:1 2 3 4 /0
现在我想要一些变量,这样我就可以将它们用作整数:a=1, a=2, a=3, a=4
我该怎么做?
到目前为止,所给出的答案是正确的,只要您的字符串格式符合预期。您应该始终检查sscanf的返回值,以确保一切正常。在上面的情况下,sscanf返回成功执行的转换数,即4。
if (4 != sscanf(buf, "%d %d %d %d", &a, &b, &c, &d))
{
/* deal with error */
}
正如其他人所指出的,如果您知道要期望多少个数字,sscanf是最简单的解决方案。否则,以下是更一般的解决方案:
首先按空格对字符串进行标记化。这个标准的C方法是使用strtok():
char* copy;
char* token;
copy = strdup(string); /* strtok modifies the string, so we need a copy */
token = strtok(copy, " ");
while(token!=NULL){
/* token now points to one number.
token = strtok(copy, " ");
}
sscanf()可以做到这一点。
#include <stdio.h>
int main(void)
{
int a, b, c, d;
sscanf("1 2 3 4", "%d %d %d %d", &a, &b, &c, &d);
printf("%d,%d,%d,%d\n", a, b, c, d);
}
sscanf(string, "%d %d %d %d", &a, &b, &c, &d);