Parsing Integer to String C

2019-01-22 13:10发布

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?

9条回答
贼婆χ
2楼-- · 2019-01-22 13:58

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-22 14:00

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.

查看更多
看我几分像从前
4楼-- · 2019-01-22 14:03

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.

查看更多
登录 后发表回答