【问题标题】:Convert char array to single int?将char数组转换为单个int?
【发布时间】:2011-08-30 21:46:59
【问题描述】:

有人知道如何将 char 数组转换为单个 int 吗?

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

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

【问题讨论】:

  • 该代码是否按原样编译?不应该。
  • 不应该这样。 convert_char_to_int(hello) 不是一个实际的函数。我在问我应该用什么函数/方法来代替我的理论:“convert_char_to_int(hello)”?
  • hello 是一个不可修改的 lvalue 所以 hello = "12345"; 甚至不会编译。
  • 好吧,这个:codepad.org/oSgK5nK4我如何转换它?
  • 您是否完全坚持使用 char 数组和 printf 等 C 风格的结构?如果没有,请查看 std::string 的字符,查看 C++ iostreams 以打印输出 (std::cout),查看 boost::lexical_cast 进行转换(正如已经指出的那样)。

标签: c++ char int


【解决方案1】:

长话短说,你必须使用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 

【讨论】:

  • 不,你不这样做,也不应该在任何新代码中使用 strtol 代替!
  • @Nim 我知道这一点,但对于像 OP 这样的新手,我想让他/她使用它是可以的,只是为了理解这个概念。我想这就是为什么其他人也建议使用相同的 api。
  • @harper 在标准 C++ 中没有 itoa。并且它的传统接口被破坏,并可能导致缓冲区溢出。
  • @Reno 在的情况下应该鼓励初学者养成坏习惯。
【解决方案2】:

Ascii 字符串到整数的转换由atoi() 函数完成。

【讨论】:

  • 那是你绝对应该避免的。如何检查错误?
【解决方案3】:

使用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 更简单、更安全。
  • 不是strtol吗?为什么strtolatoi 好?
【解决方案4】:

有多种方法可以将字符串转换为 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"); 

解决方案 3:使用 C++ Streams

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

【讨论】:

  • @Als:使用boost::lexical_castatoi 不安全!
  • +1。顺便说一句,你应该把boost::lexical_cast 放在try-catch 块中。当强制转换无效时,它会抛出 boost::bad_lexical_cast
  • ...应该使用 atoi 而不是 strtol,在这种情况下更合适 - 无需为这个简单的操作使用 boost...
  • @juanchopanza 错误代码,而不是异常。如果您正在处理用户输入(以及为什么要转换),错误代码通常比异常更合适。
  • 为什么atoi不安全?
【解决方案5】:

如果您使用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

【讨论】:

    【解决方案6】:

    我将把这个留给对没有依赖关系的实现感兴趣的人。

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

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

    【讨论】:

      【解决方案7】:

      我用:

      int convertToInt(char a[1000]){
          int i = 0;
          int num = 0;
          while (a[i] != 0)
          {
              num =  (a[i] - '0')  + (num * 10);
              i++;
          }
          return num;;
      }
      

      【讨论】:

      • @Fateh 你是不是弄错了'0'(数字零的字符,ASCII 码 48)和实际的 0 字节值,它表示字符串的结束?
      【解决方案8】:

      例如,“mcc”是一个char数组,“mcc_int”是你要获取的整数。

      char mcc[] = "1234";
      int mcc_int;
      sscanf(mcc, "%d", &mcc_int);
      

      【讨论】:

        【解决方案9】:

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

        【讨论】:

          猜你喜欢
          • 2010-12-20
          • 1970-01-01
          • 2011-11-09
          • 1970-01-01
          • 2013-12-11
          • 1970-01-01
          • 2014-03-02
          • 2021-10-15
          • 1970-01-01
          相关资源
          最近更新 更多