2011-05-23 168 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; 
    } 

适用于负值,但不能处理混合在其间的非数字字符(应该很容易添加)。只有整数。