从字符数组中读取整数

时间:2014-03-25 23:06:22

标签: c

我有一个字符串,有五个整数,用空格分隔。例如:12 33 45 0 1

我有五个变量,我想加载这些数字。是否可以多次拨打atoi?或者怎么可能呢?

char c[] = "12 33 45 0 1";
int a1, a2, a3, a4, a5;

2 个答案:

答案 0 :(得分:5)

使用strtok将字符串拆分为标记,并在每个标记上使用atoi

一个简单的例子:

    char c[] = "1 2 3";         /* our input */
    char delim[] = " ";         /* the delimiters array */
    char *s1,*s2,*s3;           /* temporary strings */
    int a1, a2, a3;             /* output */

    s1=strtok(c,delim);         /* first call to strtok - pass the original string */
    a1=atoi(s1);                /* atoi - converts a string to an int */

    s2=strtok(NULL,delim);      /* for the next calls, pass NULL instead */
    a2=atoi(s2);

    s3=strtok(NULL,delim);
    a3=atoi(s3);

关于strtok的棘手问题是我们传递了第一个标记的原始字符串,并为其他标记传递了NULL

答案 1 :(得分:1)

您也可以使用sscanf转换数字,但请务必检查返回值

if ( sscanf( c, "%d%d%d%d%d", &a1, &a2, &a3, &a4, &a5 ) != 5 )
    printf( "Well, that didn't work\n" );