Paradius
Paradius

Reputation: 8159

Parsing Integer to String C

How does one parse an integer to string(char* || char[]) in C? Is there an equivalent to the Integer.parseInt(String) method from Java in C?

Upvotes: 22

Views: 89610

Answers (9)

user3466773
user3466773

Reputation: 186

This is not an optimal solution. This is my solution given multiple restrictions, so if you had limited resources based on your course/instructor's guidelines, this may be a good fit for you.

Also note that this is a fraction of my own project implement, and I had to read in operands as well as digits, so I used getchars. Otherwise, if you only need integers and no other type of characters, I like using this:

int k;
while (scanf("%d", &k) == 1)

The rules were no specific, "advanced" C concepts: no String variables, no structs, no pointers, no methods not covered, and the only include we were allowed was #include

So with no simple method calls like atoi() available or any String variables to use, I chose to just brute force it.

1: read chars in using getchar (fgets was banned). return 1 (exit status 1) if there is an invalid character. For your problem based of parseInt in Java 1 11 13 is valid but 1 11 1a is invalid, so for all values we have a valid "string" iff all chars are 0-9 ignoring whitespace.

2: convert the ASCII value of a char to its integer value (eg. 48 => 0)

3: use a variable val to store an int such that for each char in a "substring" there is a corresponding integer digit. i.e. "1234" => 1234 append this to an int array and set val to 0 for reuse.

The following code demonstrates this algorithm:

int main() {
    int i, c;
    int size = 0;
    int arr[10]; //max number of ints yours may differ
    int val = 0;
    int chars[1200]; //arbitrary size to fit largest "String"
    int len = 0;

    //Part 1: read in valid integer chars from stdin
    while((c = getchar()) != EOF && (c < 58 && c > 47)) {
        chars[len] = c;
        len++;
     }

    //Part 2: Convert atoi manually. concat digits of multi digit integers and  
    //        append to an int[]
    for(i = 0; i < len; i++){
    for(i = 0; i < len; i++){
        if(chars[i] > 47 && chars[i] < 58){
        while((chars[i] > 47 && chars[i] < 58)){
            if(chars[i] == 48)
                c = 0;
            if(chars[i] == 49)
                c = 1;
            if(chars[i] == 50)
                c = 2;
            if(chars[i] == 51)
                c = 3;
            if(chars[i] == 52)
                c = 4;
            if(chars[i] == 53)
                c = 5;
            if(chars[i] == 54)
                c = 6;
            if(chars[i] == 55)
                c = 7;
            if(chars[i] ==56)
                c = 8;
            if(chars[i] == 57)
                 c = 9;
            val = val*10 + c;
            i++;
        }
        arr[size] = val;
        size++;
        if(size > 10) //we have a check to ensure size stays in bounds
           return 1;
        val = 0;
        }
        //Print: We'll make it a clean, organized "toString" representation
        printf("[");
        for(i = 0; i < size-1; i++){
            printf("%d, ", arr[i]); 
        }
        printf("%d]", arr[i];

        return 0;

Again, this is the brute force method, but in cases like mine where you can't use the method concepts people use professionally or various C99 implements, this may be what you are looking for.

Upvotes: -1

SuperKael
SuperKael

Reputation: 226

You can try:

int intval;
String stringval;
//assign a value to intval here.
stringval = String(intval);

that should do the trick.

Upvotes: 0

anon
anon

Reputation:

You may want to take a look at the compliant solution on this site.

Upvotes: 0

vinc456
vinc456

Reputation: 2890

This is discussed in Steve Summit's C FAQs.

Upvotes: 2

please delete me
please delete me

Reputation:

It sounds like you have a string and want to convert it to an integer, judging by the mention of parseInt, though it's not quite clear from the question...

To do this, use strtol. This function is marginally more complicated than atoi, but in return it provides a clearer indication of error conditions, because it can fill in a pointer (that the caller provides) with the address of the first character that got it confused. The caller can then examine the offending character and decide whether the string was valid or not. atoi, by contrast, just returns 0 if it got lost, which isn't always helpful -- though if you're happy with this behaviour then you might as well use it.

An example use of strtol follows. The check for error is very simple: if the first unrecognised character wasn't the '\x0' that ends the string, then the string is considered not to contain a valid int.

int ParseInt(const char *s,int *i)
{
    char *ep;
    long l;

    l=strtol(s,&ep,0);

    if(*ep!=0)
        return 0;

    *i=(int)l;
    return 1;
 }

This function fills in *i with the integer and returns 1, if the string contained a valid integer. Otherwise, it returns 0.

Upvotes: 10

jpalecek
jpalecek

Reputation: 47762

If you want to convert an integer to string, try the function snprintf().

If you want to convert a string to an integer, try the function sscanf() or atoi() or atol().

Upvotes: 49

Paul
Paul

Reputation: 6439

To convert an int to a string:

int x = -5;
char buffer[50];
sprintf( buffer, "%d", x );

You can also do it for doubles:

double d = 3.1415;
sprintf( buffer, "%f", d );

To convert a string to an int:

int x = atoi("-43");

See http://www.acm.uiuc.edu/webmonkeys/book/c_guide/ for the documentation of these functions.

Upvotes: 16

Matthew Scharley
Matthew Scharley

Reputation: 132264

You can also check out the atoi() function (ascii to integer) and it's relatives, atol and atoll, etc.

Also, there are functions that do the reverse as well, namely itoa() and co.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 993085

The Java parseInt() function parses a string to return an integer. An equivalent C function is atoi(). However, this doesn't seem to match the first part of your question. Do you want to convert from an integer to a string, or from a string to an integer?

Upvotes: 1

Related Questions