¿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);
¿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);
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
ASCII a entero conversión se realiza mediante el atoi()
función.
Esa es una que definitivamente deberías evitar. ¿Cómo verifica los errores? –
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;
}
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. –
¿No es 'strtol'? ¿Por qué 'strtol' es mejor que' atoi'? – qed
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.
}
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()
.
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
¿Compila ese código como está? No debería. –
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
'hello' es un * lvalue * no modificable así que' hello = "12345"; 'ni siquiera compilará. –