31

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);
Shweta
  • 5,198
  • 11
  • 44
  • 58
IsThisTheEnd
  • 311
  • 1
  • 3
  • 3
  • 1
    Does that code compile as is? It shouldn't. – Chris Lutz May 23 '11 at 06:09
  • It's not supposed to. convert_char_to_int(hello) is not an actual function. I'm asking what function/method I should use to replace my theoretical: "convert_char_to_int(hello)" ? – IsThisTheEnd May 23 '11 at 06:10
  • 2
    `hello` is a non modifiable *lvalue* so `hello = "12345";` won't even compile. – Prasoon Saurav May 23 '11 at 06:10
  • All right then, this one: http://codepad.org/oSgK5nK4 How do I convert it? – IsThisTheEnd May 23 '11 at 06:13
  • 1
    Are you absolutely stuck with C-style constructs like char arrays and printf? If not, have a look at `std::string` for the characters, C++ iostreams for printing the output (`std::cout`), and `boost::lexical_cast` for the conversion (as has already been pointed out). – juanchopanza May 23 '11 at 06:47
  • you assign 6 characters to an array with a size of 5. Remember your null terminator. You'd better use strings. And if you can't then at least initialize at declaration time to avoid issues like that. `char hello[] = "12345";` – FalcoGer Aug 14 '20 at 08:59

9 Answers9

46

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.      
} 
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 3
    @Als: Use `boost::lexical_cast`. `atoi` is not safe! – Nawaz May 23 '11 at 06:15
  • @Nawaz: I guess that sums it all up :) – Alok Save May 23 '11 at 06:28
  • 1
    +1. By the way, you should put `boost::lexical_cast` in try-catch block. It throws `boost::bad_lexical_cast` when the cast is invalid. – Nawaz May 23 '11 at 06:38
  • 6
    ...instead of `atoi` `strtol` should be used and in this case is more apt - no need to use boost just for this simple operation... – Nim May 23 '11 at 06:51
  • @Nim But what is wrong with using boost, even for this simple example? What does using strtol gain you? – juanchopanza May 23 '11 at 07:05
  • 1
    @juanchopanza An error code, rather than an exception. If you're handling user input (and why else would you be converting), error codes are generally more appropriate than exceptions. – James Kanze May 23 '11 at 08:38
  • @juanchopanza, there were (and still are perfectly good) ways of doing things before boost came along - don't get me wrong, I'm a huge fan of boost (if you see my answers you'll realise this), however, sometimes there are are far simpler and more appropriate ways of doing things... :) – Nim May 23 '11 at 08:45
  • @Nim, sure, I was just curious as to why it might be more appropriate. @James Kanze has mentioned error codes vs. exceptions. Personally I use boost::lexical_cast everywhere and haven't come across a situation where it didn't seem appropriate. – juanchopanza May 23 '11 at 08:55
  • 1
    Why is atoi not safe? – qed Nov 06 '13 at 18:13
  • 1
    What about the stoi and stol functions in c++11? For example `std::stoi("1234")` – qed Nov 06 '13 at 21:21
11

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

Community
  • 1
  • 1
Rick Smith
  • 9,031
  • 15
  • 81
  • 85
3

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;;
}
Trần Hiệp
  • 101
  • 1
  • 2
  • @Fateh aren't you mistaking '0' (character for digit zero, ASCII code 48) and actual 0 byte value, which signalizes end of a string? – user1079505 Jun 30 '21 at 18:13
1

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.

Holly
  • 43
  • 4
1

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;
}
  • Not like that, at any rate. Never use a `"%s"`, for example, since that will result in buffer overflow. All in all, `stdtol` is a lot simpler and safer. – James Kanze May 23 '11 at 08:39
  • 1
    Isn't `strtol`? Why is `strtol` better than `atoi`? – qed Nov 06 '13 at 20:43
  • @qed For atoi, "if the value of the result cannot be represented, the behavior is undefined". With strtol, the behavior is defined for all input. – William Pursell Sep 26 '22 at 21:40
1

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);
Priteem
  • 11
  • 4
0

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;
}
sntrcode
  • 202
  • 1
  • 7
  • 10
-1

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

harper
  • 13,345
  • 8
  • 56
  • 105
-2

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 
Reno
  • 33,594
  • 11
  • 89
  • 102
  • 2
    No you don't and you should not in any new code - use `strtol` instead! – Nim May 23 '11 at 06:50
  • @Nim I'm aware of that, but for a newbie like OP, I guess its ok to let him/her use it, just for the sake of understanding this concept. I guess that is why others have suggested the same api too. – Reno May 23 '11 at 06:57
  • @harper There is no `itoa` in standard C++. And the traditional interface for it is broken, and can result in buffer overflows. – James Kanze May 23 '11 at 08:42
  • 2
    @Reno In **no** case should a beginner be encouraged to develop bad habits. – James Kanze May 23 '11 at 08:42