2014-03-25 118 views
0

我有一個字符串,有五個整數,用空格分隔。例如:12 33 45 0 1從字符數組讀取整數

我有五個變量,我想加載這些數字。是否可以撥打atoi更多次?或者它甚至可能如何?

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

你可能需要學習一個其他的概念,稱爲*陣列*。 –

回答

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爲其他標記。

+0

你敢把這樣的代碼片段放在這裏嗎?否則,你的答案似乎太短,並且會更適合評論,而不是完整的答案。 –

+0

@JanVlinsky - 你是對的。感謝您的評論。 – Benesh

1

您還可以使用sscanf將數字轉換,但一定要檢查返回值

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