有人知道如何将字符数组转换为单个整数吗?
char hello[5];
hello = "12345";
int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);
将字符串转换为整数有多种方法。
解决方案1:使用Legacy 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");
解决方案3:使用C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
boost::lexical_cast
。 atoi
不安全! - Nawazboost::lexical_cast
放在 try-catch 块中。当转换无效时,它会抛出 boost::bad_lexical_cast
异常。 - Nawazstrtol
而不是atoi
,在这种情况下更加适合-没有必要仅为这个简单的操作而使用boost。 - Nimstd::stoi("1234")
。 - qedtry {
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.
}
stoi()
函数之前,“1234abc”从一个 char[]
隐式转换为 std:string
。保留implicitly converted链接。我使用:
int convertToInt(char a[1000]){
int i = 0;
int num = 0;
while (a[i] != 0)
{
num = (a[i] - '0') + (num * 10);
i++;
}
return num;;
}
使用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;
}
"%s"
,因为那会导致缓冲区溢出。总的来说,stdtol
更简单、更安全。 - James Kanzestrtol
不是更好吗?为什么strtol
比atoi
更好? - qedchar mcc[] = "1234";
int mcc_int;
sscanf(mcc, "%d", &mcc_int);
我只是将这个留在这里,供那些对没有依赖关系的实现感兴趣的人参考。
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;
}
使用 cstring 和 cmath 库:
int charsToInt (char* chars) {
int res{ 0 };
int len = strlen(chars);
bool sig = *chars == '-';
if (sig) {
chars++;
len--;
}
for (int i{ 0 }; i < len; i++) {
int dig = *(chars + i) - '0';
res += dig * (pow(10, len - i - 1));
}
res *= sig ? -1 : 1;
return res;
}
将Ascii字符串转换为整数是通过atoi()
函数完成的。
strtol
! - Nimitoa
函数。传统接口已经过时,可能导致缓冲区溢出。 - James Kanze
hello = "12345";
甚至无法编译。 - Prasoon Sauravstd::string
来处理字符,使用C++ iostreams来打印输出(std::cout
),并使用boost::lexical_cast
进行转换(正如已经指出的那样)。 - juanchopanzachar hello[] = "12345";
- FalcoGer