开发者

Convert char array to single int?

开发者 https://www.devze.com 2023-03-07 22:12 出处:网络
Anyone know how to convert a char array to a single int? char hello[5]; hello = \"12345\"; int myNumber = convert_char_to_int(hello);

Anyone know how to convert a char array to a single int?

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

int myNumber = convert_char_to_int(hello);
Printf("My number i开发者_如何学运维s: %d", myNumber);


There are mulitple ways of converting a string to an int.

Solution 1: Using Legacy C functionality

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

    char hello[] = "12345";

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

    return 0;
}

Solution 2: Using lexical_cast(Most Appropriate & simplest)

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

Solution 3: Using C++ Streams

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


If you are using C++11, you should probably use stoi because it can distinguish between an error and parsing "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.
}

It should be noted that "1234abc" is implicitly converted from a char[] to a std:string before being passed to stoi().


I use :

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


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


I'll just leave this here for people interested in an implementation with no dependencies.

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

Works with negative values, but can't handle non-numeric characters mixed in between (should be easy to add though). Integers only.


For example, "mcc" is a char array and "mcc_int" is the integer you want to get.

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


With cstring and 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 string to integer conversion is done by the atoi() function.


Long story short you have to use atoi()

ed:

If you are interested in doing this 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 
0

精彩评论

暂无评论...
验证码 换一张
取 消