2017-04-07 106 views
-2

我有一個字符串char * a ='343'。我想將其轉換爲整數值。從char *轉換爲int

例子。 char * a =「44221」 我想將該值存入int a;

+2

''343''不是字符串 –

回答

1

這應該有助於

#include <stdlib.h> 

inline int to_int(const char *s) 
{ 
    return atoi(s); 
} 

以防萬一爲例用法

int main(int ac, char *av[]) 
{ 
    printf(" to_int(%s) = %d " ,av[1] , to_int(av[1])); 
    return 0; 
} 
+0

- 在該包裝中閃爍兩次 - – Sebivor

4

這是最C運行庫的一部分:

#include <stdlib> 

char *a = "1234"; 
int i = atoi(a); 

這就是atoi功能。請仔細閱讀各種可用的方法。 C的圖書館非常精簡,所以不用多久。

+0

['atoi'有害](https://blog.mozilla.org/nnethercote/2009/03/13/atol-considered-harmful/)和[shouldn' (http://stackoverflow.com/q/17710018/995714) –

3

有幾種方法,以一個字符串(在一個char *指出)轉換成int

我在這裏列出其中的一些:
讓我們假設您有一個字符串str decl ARED爲:

char *str = "44221"; 
  1. INT A =的atoi(STR);
    這將返回由str指向的字符串轉換的int值。雖然方便,但當用戶提供無效輸入時,此功能不會執行準確的錯誤報告。

  2. 使用的sscanf():這類似於通常的scanf除了它從一個字符串,而不是從stdin讀取輸入。

    int a; 
    int v = sscanf(str, "%d", &a); 
    // XXX: v should be 1 since 1 conversion is performed; handle the conversion error if it isn't 
    
  3. strtol將:此轉換給定的字符串轉換爲長整型。文檔發現在:http://man7.org/linux/man-pages/man3/strtol.3.html

    一般用法:

    char *ptr; 
    long a = strtol(str, &ptr, base); 
    

第一個無效字符(不是數字)的地址存儲在ptr。基地是默認10

  • 通過迭代字符值:爲什麼取決於當你可以編寫自己的程序來實現這個庫?這並不難。這樣你甚至可以執行所需的驗證/錯誤檢查。

    示例代碼:

    unsigned char ch; 
    int a = 0; 
    // Add checks to see if the 1st char of the string is a '+' or '-'. 
    for (i = 0; i < strlen(str); i++) { 
        ch = str[i]; 
        //Add error checks to see if ch is a digit or not (e.g. using isdigit from <ctype.h>). 
        a = a*10 + (ch - '0'); 
    } 
    
  • 希望這有助於!