2011-04-26 95 views
0

我傳遞一個參數傳遞給一個C程序:轉換陣列用C

程序名1234

int main (int argc, char *argv[]) { 

    int  length_of_input = 0;  
    char* input   = argv[1]; 


    while(input[length_of_input]) { 
     //convert input from array of char to int 
     length_of_input++; 
    } 
} 

我希望能夠使用每個作爲整數分別傳遞給函數的參數的數字。 atoi(input [])會引發編譯時錯誤。

此代碼不能編譯:

while(input[length_of_input]) { 
    int temp = atoi(input[length_of_input]); 
    printf("char %i: %i\n", length_of_input, temp); 
    length_of_input++; 
} 
+0

請更精確的你想要什麼。你期望一個包含{1,2,3,4}的int []嗎?此外,這聽起來像作業,所以標記爲 – 2011-04-26 21:51:50

+1

肯定它是一個較大的家庭作業的一小部分,你可能已經看到我今天問過的其他問題。但我不認爲它需要被標記爲這樣,因爲這是一個微不足道的語言問題。 – 2011-04-26 21:56:01

回答

4
int i; 
for (i = 0; input[i] != 0; i++){ 
    output[i] = input[i] - '0'; 
} 
+5

您忘記了終止每個字符......您將以包含{1234,234,34,4}的整數組結束。 – Lou 2011-04-26 21:55:47

+1

'output [i] = input [i] - '0';' – 2011-04-26 22:01:02

+0

@Lou和@Conrad你是對的,沒有理由使用atoi如果我們要轉換單個字符(如果它不是null結尾,會遇到問題> _ <) – Thebigcheeze 2011-04-26 22:02:54

1

看到,因爲這是家庭作業,你也可以做

output[i] = input[i] - '0'; 

但要小心input[i]實際上是一個數字(即它的'0''9'之間)!

1

首先,您必須檢查需要爲整數數組分配多少空間。這可以用strlen()函數完成,也可以迭代通過字符串並檢查找到了多少有效字符。然後,您必須遍歷字符串並將每個(有效)字符轉換爲等效的整數。這裏很難使用atoi()scanf()系列函數,因爲它們除了數組作爲輸入外。更好的解決方案是編寫你自己的小轉換器函數或片段進行轉換。

這是一個小的示例應用程序,它將字符串轉換爲整數的數組。如果該字符不是有效的十進制數字,則將-1放入數組中。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char *argv[]) 
{ 
    int length, i; 
    int *array; 
    char *input = argv[1]; 

    /* check if there is input */ 
    if(input == NULL) return EXIT_FAILURE; 

    /* check the length of the input */ 
    length = strlen(input); 
    if(length < 1) return EXIT_FAILURE; 

    /* allocate space for the int array */ 
    array = malloc(length * sizeof *array); 
    if(array == NULL) return EXIT_FAILURE; 

    /* convert string to integer array */ 
    for(i = 0; i < length; ++i) { 
     if(input[i] >= '0' && input[i] <= '9') 
      array[i] = input[i] - '0'; 
     else 
      array[i] = -1; /* not a number */ 
    } 

    /* print results */ 
    for(i = 0; i < length; ++i) 
     printf("%d\n", array[i]); 

    /* free the allocated memory */ 
    free(array); 

    return EXIT_SUCCESS; 
} 

還要檢查這些問題: