-1

I have a string char * a = '343'. I want to convert it into integer value.

Example. char *a = "44221" I want to store that value into into int a;

Vaibhav Borkar
  • 171
  • 2
  • 12

3 Answers3

4

This is is part of most C runtimes:

#include <stdlib>

char *a = "1234";
int i = atoi(a);

That's the atoi function. Do read through the various methods available. C's library is pretty lean so it won't take long.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • [`atoi` is harmful](https://blog.mozilla.org/nnethercote/2009/03/13/atol-considered-harmful/) and [shouldn't be used](http://stackoverflow.com/q/17710018/995714) – phuclv Apr 10 '17 at 14:37
3

There are several ways to convert a string (pointed at by a char *) into an int:

I'm listing few of them here:
Let's assume you have a string str declared as:

char *str = "44221";
  1. int a = atoi(str);
    This returns the int value converted from the string pointed at by str. Although convenient, this function does not perform accurate error reporting when user supplies an invalid input.

  2. Using sscanf(): This is similar to the usual scanf except that it reads input from a string rather than from stdin.

    int a;
    int v = sscanf(str, "%d", &a);
    // XXX: v should be 1 since 1 conversion is performed; handle the conversion error if it isn't
    
  3. strtol: This converts a given string to a long integer. Documentation found at: http://man7.org/linux/man-pages/man3/strtol.3.html

    General usage:

    char *ptr; 
    long a = strtol(str, &ptr, base);
    

The address of the first invalid character (not a digit) is stored in ptr. Base is by default 10.

  1. Iterating through character values: Why depend on libraries when you can write your own routine to achieve this? It isn't hard at all. That way you can even perform the required validation/error checking.

    Sample code:

    unsigned char ch;   
    int a = 0;
    // Add checks to see if the 1st char of the string is a '+' or '-'.
    for (i = 0; i < strlen(str); i++) { 
        ch = str[i]; 
       //Add error checks to see if ch is a digit or not (e.g. using isdigit from <ctype.h>).
        a = a*10 + (ch - '0');
    }
    

Hope this helps!

paratrooper
  • 434
  • 1
  • 10
  • 18
2

This should help

#include <stdlib.h>

inline int to_int(const char *s)
{
    return atoi(s);
}

just in case for an example usage

int main( int ac, char *av[] )
{
    printf(" to_int(%s) = %d " ,av[1] , to_int(av[1]) );
    return 0;
}
asio_guy
  • 3,667
  • 2
  • 19
  • 35