2011-05-23 163 views
19

任何人都知道如何將char數組轉換爲單個int?將char數組轉換爲單個int?

char hello[5]; 
hello = "12345"; 

int myNumber = convert_char_to_int(hello); 
Printf("My number is: %d", myNumber); 
+1

該代碼是否按原樣編譯?它不應該。 – 2011-05-23 06:09:00

+0

這不應該。 convert_char_to_int(hello)不是一個實際的函數。我問什麼函數/方法我應該用來取代我的理論:「convert_char_to_int(hello)」? – IsThisTheEnd 2011-05-23 06:10:44

+1

'hello'是一個不可修改的*左值*所以'hello =「12345」;'甚至不會編譯。 – 2011-05-23 06:10:53

回答

0

長話短說,你必須使用atoi()

編輯:

如果你有興趣做這個the right way

char szNos[] = "12345"; 
char *pNext; 
long output; 
output = strtol (szNos, &pNext, 10); // input, ptr to next char in szNos (null here), base 
+4

錯誤的功能,不好的建議。 – Mat 2011-05-23 06:11:45

+0

我讀了這個問題錯了soz。 – Reno 2011-05-23 06:12:20

+0

不,你不應該在任何新的代碼 - 使用'strtol'代替! – Nim 2011-05-23 06:50:18

-1

ASCII字符串到整數的轉換是由完成atoi()功能。

+2

這是你應該避免的。你如何檢查錯誤? – 2011-05-23 08:37:15

1

使用sscanf

/* sscanf example */ 
#include <stdio.h> 

int main() 
{ 
    char sentence []="Rudolph is 12 years old"; 
    char str [20]; 
    int i; 

    sscanf (sentence,"%s %*s %d",str,&i); 
    printf ("%s -> %d\n",str,i); 

    return 0; 
} 
+0

不管怎樣,都不是這樣。例如,不要使用'「%s」',因爲這會導致緩衝區溢出。總而言之,'stdtol'更簡單,更安全。 – 2011-05-23 08:39:39

+1

是不是'strtol'?爲什麼'strtol'比'atoi'好? – qed 2013-11-06 20:43:29

25

有一個字符串轉換爲一個int的多張的方式。

解決方案1:使用傳統C功能

int main() 
{ 
    //char hello[5];  
    //hello = "12345"; --->This wont compile 

    char hello[] = "12345"; 

    Printf("My number is: %d", atoi(hello)); 

    return 0; 
} 

解決方案2:使用lexical_cast(最適當&簡單)

int x = boost::lexical_cast<int>("12345"); 

SOLU重刑3:使用C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x; 
str >> x; 
if (!str) 
{  
    // The conversion failed.  
} 
+3

@Als:使用'boost :: lexical_cast'。 'atoi'不安全! – Nawaz 2011-05-23 06:15:53

+0

@Nawaz:我想這一切總結起來:) – 2011-05-23 06:28:07

+1

+1。順便說一句,你應該把'boost :: lexical_cast'放在try-catch塊中。當劇組無效時它會拋出'boost :: bad_lexical_cast'。 – Nawaz 2011-05-23 06:38:31

4

如果您正在使用C++11,你應該使用stoi,因爲它可以錯誤和解析"0"區分。

try { 
    int number = std::stoi("1234abc"); 
} catch (std::exception const &e) { 
    // This could not be parsed into a number so an exception is thrown. 
    // atoi() would return 0, which is less helpful if it could be a valid value. 
} 

應當指出的是,「1234abc」是被傳遞到stoi()char[]std:stringimplicitly converted

0

我會在這裏留給這個對沒有依賴關係的實現感興趣的人。

inline int 
stringLength (char *String) 
    { 
    int Count = 0; 
    while (*String ++) ++ Count; 
    return Count; 
    } 

inline int 
stringToInt (char *String) 
    { 
    int Integer = 0; 
    int Length = stringLength(String); 
    for (int Caret = Length - 1, Digit = 1; Caret >= 0; -- Caret, Digit *= 10) 
     { 
     if (String[Caret] == '-') return Integer * -1; 
     Integer += (String[Caret] - '0') * Digit; 
     } 

    return Integer; 
    } 

適用於負值,但不能處理混合在其間的非數字字符(應該很容易添加)。只有整數。