IsThisTheEnd
IsThisTheEnd

Reputation: 311

Convert char array to single int?

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 is: %d", myNumber);

Upvotes: 31

Views: 184966

Answers (9)

sntrcode
sntrcode

Reputation: 222

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

Upvotes: 0

Priteem
Priteem

Reputation: 11

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

Upvotes: 1

Trần Hiệp
Trần Hiệp

Reputation: 101

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

Upvotes: 3

harper
harper

Reputation: 13690

Ascii string to integer conversion is done by the atoi() function.

Upvotes: -1

Holly
Holly

Reputation: 43

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.

Upvotes: 1

Rick Smith
Rick Smith

Reputation: 9251

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().

Upvotes: 11

Reno
Reno

Reputation: 33792

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 

Upvotes: -2

Alok Save
Alok Save

Reputation: 206526

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

Upvotes: 46

user184968
user184968

Reputation:

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

Upvotes: 1

Related Questions