-2
"123456\000\";\"Bilka\";\"Tilst afdelingen\";\"Ager\370vej 7\";\"Port 39\";\"8381\";\"Tilst\";\"25\";\"100\";\"125\";\"90\";\"Phi"

I need to get the first 123456 and store it as an int, how can i do this?

2
  • 1
    The problem description is incomplete. Do you need to parse just this one line and once? Do you need to parse many such lines? Do you know if the number will change or will it always be 6 digits? Show us some code you've written.
    – dirkgently
    Apr 30, 2012 at 7:45
  • Your description isn't entirely clear. Is this intended to be a C string literal, or is it (for example) a string as it comes in from the outside world, so the `\0' is really two characters, a backslash and a digit 0? Apr 30, 2012 at 7:48

4 Answers 4

2

Use atoi(3)

int n = atoi("123456\000\";\"Bilka\";\"Tilst afdelingen\";\"Ager\370vej 7\";\"Port 39\";\"8381\";\"Tilst\";\"25\";\"100\";\"125\";\"90\";\"Phi"

);

1

Use sscanf().

char *str = "123456\000\";\"Bilka\";\"Tilst afdelingen\";\"Ager\370vej 7\";\"Port 39\";\"8381\";\"Tilst\";\"25\";\"100\";\"125\";\"90\";\"Phi";
int num = 0;

sscanf(str, "%d", &num);
printf(" The extracted number is %d.\n", num);
1

Use strtol(), it does better error reporting than atoi().

0

You can use atoi or the below program.. However the below one is not advised as it is not portable and makes an assumption that the machine uses acsii character set.

#include <stdio.h>

int atoi_1(char a[])
{
    int n=0;

    if (a[0] >= '0' && a[0] <= '9') {
        n = a[0]-'0';
    } else {
        /* exception - a[0] is not an integer */
        printf("exception - a[0] is not an integer \n");
    }

    return n;
}

int main()
{
    char a[] = "123456\000\";\"Bilka\";\"Tilst afdelingen\";\"Ager\370vej 7\";\"Port 39\";\"8381\";\"Tilst\";\"25\";\"100\";\"125\";\"90\";\"Phi";

    printf("a[0] = %d \n", atoi_1(a));
    return 0;
} 

Output:

$ gcc atoi.c 
$ ./a.out 
a[0] = 1 
$
2
  • Use isdigit instead of the '0' - '9' range based checks.
    – dirkgently
    Apr 30, 2012 at 7:57
  • will also work for EBCDIC. However, I have no idea why anyone would not use isdigit.
    – user93353
    Dec 6, 2012 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.