简体   繁体   English

如何将char *转换为int?

[英]How do I convert a char* to an int?

I need to convert a char* to an integer. 我需要将char *转换为整数。 For example: 例如:

data.SetBytFldPos(*attribute->value());

The value in the attribute class is a char*. 属性类中的值是char *。 'SetBytFldPos" takes an int. 'SetBytFldPos'采用int。

Lots of ways. 很多方法。 Simplest is to use the strtol() function . 最简单的方法是使用strtol()函数

You don't convert char* to an int. 您不将char *转换为int。 You may wish to parse a decimal string. 您可能希望解析十进制字符串。 This is done by atoi(). 这是由atoi()完成的。 atoi("1") == 1. atoi(“1”)== 1。

If you need to make sure that your char* represents a valid int, you can use Boost Lexical Cast 如果你需要确保你的char *代表一个有效的int,你可以使用Boost Lexical Cast

#include <boost/lexical_cast.hpp>

try {
    data.SetBytFldPos(boost::lexical_cast<int>(*attribute->value()));
} catch (bad_lexical_cast) {
    // something is wrong
}

You can also write a generic "convert string-to-X template". 您还可以编写通用的“转换字符串到X模板”。

template <class T>
T parse(const std::string& s)
{
  T out;
  std::stringstream ss(s);
  ss >> out;
  return out;
}

Usage: 用法:

int x = parse<int>("123");
float y = parse<float>("3.14159");

There are four ways I can think of: 我能想到四种方式:

  • atoi . atoi Be warned that this function returns 0 if it can't parse your string. 如果它无法解析您的字符串,请注意此函数返回0。
  • strtol , a more robust version of atoi . strtol ,一个更强大的atoi版本。 This might cause a compiler warning because you need an int and its return value is long . 这可能会导致编译器警告,因为您需要一个int并且其返回值很long
  • Boost library's lexical_cast . 提升图书馆的lexical_cast I like this one if you can use Boost. 如果你可以使用Boost,我喜欢这个。
  • Use a stringstream , as shown below. 使用stringstream ,如下所示。

Code sample: 代码示例:

std::string str(*attribute->value());
std::istringstream myStrm(str);
int val;

myStrm >> val;

你可以使用atoi()函数

data.SetByteFldPos(atoi(attribute->value()));

There is a simple C function called atoi which is not so good because the error handling is in best case unintuitively and easy to forget. 有一个名为atoi的简单C函数,它不是很好,因为错误处理在最好的情况下是不直观且容易忘记的。 The (C) function strtol is much better, make it a habit to prefer that one to atoi. (C)函数strtol要好得多,习惯优先选择atoi。 Here is example code from the man page: 以下是手册页中的示例代码:

   #include <stdlib.h>
   #include <limits.h>
   #include <stdio.h>
   #include <errno.h>

   int
   main(int argc, char *argv[])
   {
       int base;
       char *endptr, *str;
       long val;

       if (argc < 2) {
           fprintf(stderr, "Usage: %s str [base]\n", argv[0]);
           exit(EXIT_FAILURE);
       }

       str = argv[1];
       base = (argc > 2) ? atoi(argv[2]) : 10;

       errno = 0;    /* To distinguish success/failure after call */
       val = strtol(str, &endptr, base);

       /* Check for various possible errors */

       if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
               || (errno != 0 && val == 0)) {
           perror("strtol");
           exit(EXIT_FAILURE);
       }

       if (endptr == str) {
           fprintf(stderr, "No digits were found\n");
           exit(EXIT_FAILURE);
       }

       /* If we got here, strtol() successfully parsed a number */

       printf("strtol() returned %ld\n", val);

       if (*endptr != '\0')        /* Not necessarily an error... */
           printf("Further characters after number: %s\n", endptr);

       exit(EXIT_SUCCESS);
   }

Notice the total lack of any kind of error check for the atoi(argv[2]) conversion. 注意atoi(argv[2])转换完全没有任何错误检查。 Not that strtol is super simple and intuitive to check for errors either, but it is at least better. 并非strtol非常简单直观地检查错误,但它至少更好。

You can 您可以

// needed
#include <sstream>

// source, target
char const * p = "123";
int ival;

// conversion
std::stringstream ss(p);
ss >> ival;

Note though that we usually talk about "strings", not char*, as long as we don't mean pointers. 请注意,我们通常只谈论“字符串”,而不是char *,只要我们不指代指针。

I believe this will do the trick. 我相信这会成功。

int pow(int a, int b)                                                                                                                                                                                                                                                                               
{                                                                                                                                                                                                                                                                                                   
    int val = 1;                                                                                                                                                                                                                                                                                    
    for (int i = 0; i < b; i++)                                                                                                                                                                                                                                                                     
        val *= a;                                                                                                                                                                                                                                                                                   
    return val;                                                                                                                                                                                                                                                                                     
}                                                                                                                                                                                                                                                                                                     

int cp_length(char* cp)                                                                                                                                                                                                                                                                             
{                                                                                                                                                                                                                                                                                                   
    int i = 0;                                                                                                                                                                                                                                                                                      
    while (cp [i] != '\0')                                                                                                                                                                                                                                                                          
        i++;                                                                                                                                                                                                                                                                                        
    return i;                                                                                                                                                                                                                                                                                       
}                                                                                                                                                                                                                                                                                                   

int cptoi(char* cp)                                                                                                                                                                                                                                                                                 
{                                                                                                                                                                                                                                                                                                   
    int val = 0;                                                                                                                                                                                                                                                                                    
    for (int j = cp_length(cp) - 1, i = 0; j >= 0; j--, i++)                                                                                                                                                                                                                                        
        if (cp [i] < 0x30 || cp [i] > 0x39) // if the character is not a digit                                                                                                                                                                                                                      
            continue;                                                                                                                                                                                                                                                                               
        else                                                                                                                                                                                                                                                                                        
            val += (cp [0] == '-' ? -(cp [i] - 0x30) * pow(10, j) : +(cp [i] - 0x30) * pow(10, j)); // accounts for negativity                                                                                                                                                                      

    // This is the thing you need.
    return val;                                                                                                                                                                                                                                                                                     
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM