2011-05-23 11 views
19

¿Alguien sabe cómo convertir una matriz de caracteres a una sola int?¿Convertir una matriz de caracteres a una sola int?

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

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

¿Compila ese código como está? No debería. –

+0

Se supone que no. convert_char_to_int (hello) no es una función real. Me pregunto qué función/método debo usar para reemplazar mi teoría: "convert_char_to_int (hello)"? – IsThisTheEnd

+1

'hello' es un * lvalue * no modificable así que' hello = "12345"; 'ni siquiera compilará. –

Respuesta

0

breve larga historia que tiene que utilizar atoi()

ed:

Si usted está interesado en hacer esto the right way: cadena

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

función incorrecta, mal consejo. – Mat

+0

Lo leí la pregunta incorrectamente soz. – Reno

+0

No, no es así y no deberías incluir ningún código nuevo; ¡usa 'strtol' en su lugar! – Nim

-1

ASCII a entero conversión se realiza mediante el atoi() función.

+2

Esa es una que definitivamente deberías evitar. ¿Cómo verifica los errores? –

1

Uso 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

No es así, en cualquier caso. Nunca use un '"% s "', por ejemplo, ya que eso provocará un desbordamiento del búfer. En general, 'stdtol' es mucho más simple y seguro. –

+1

¿No es 'strtol'? ¿Por qué 'strtol' es mejor que' atoi'? – qed

25

hay maneras Mulitple de convertir una cadena a un entero.

Solución 1: Uso de funcionalidad Legado C

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

    char hello[] = "12345"; 

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

    return 0; 
} 

Solución 2: Uso de lexical_cast (más apropiado & más simple)

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

Solu ción 3: Uso de C++ Streams

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

@Als: use 'boost :: lexical_cast'. 'atoi' no es seguro! – Nawaz

+0

@Nawaz: supongo que lo resume todo :) –

+1

+1. Por cierto, deberías poner 'boost :: lexical_cast' en el bloque try-catch. Lanza 'boost :: bad_lexical_cast' cuando el elenco no es válido. – Nawaz

4

Si está utilizando C++11, probablemente debería utilizar stoi porque puede distinguir entre un error y analizar "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. 
} 

Cabe señalar que "1234abc" es implicitly converted de un char[] a un std:string antes de ser pasado a stoi().

0

Voy a dejar esto aquí para las personas interesadas en una implementación sin dependencias.

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; 
    } 

Obras con valores negativos, pero no puede manejar caracteres no numéricos mezclados entre (debe ser fácil de añadir sin embargo). Enteros solamente

Cuestiones relacionadas