0

I have a very basic question, if I have a string of chars like this: char charv1[6] = "v445" or v666 How can I get the numbers and turn them into a single integer with value: 445 or 666?

I have been trying this code but something goes wrong ...:

            size = (strlen(charv1)-1);
            for(aux = size; aux > 0; aux--){
                if(aux == (size)){
                    v1 = charv1[aux]-'0';
                }
                else{

                    aux2 = (charv1[aux]-'0')*10;
                    printf("%d\n", aux2);
                    v1 = v1 + aux2;
                }
            }

charv1 contains the string: v445etc

I remember a few years ago, I did it recursively but I do not remember how, but now I do not need an elegant solution ... I need one that just works.

4

5 回答 5

2

只需使用strtol

long int num;
char* end;
num = strtol(&charv1[1], &end, 10);
于 2013-10-17T21:57:03.267 回答
2

有一个函数叫做strtol(),它是这样使用的:

 long dest = 0;
    char source[10] = "122";

    dest = strtol(source , NULL , 10); // arg 1 : the string to be converted arg2 : allways NULL arg3 : the base (16 for hex , 10 for decimal , 2 for binary ...)

但在你的情况下,你应该用这个替换dest = strtol(source , NULL , 10);dest = strtol((source + 1) , NULL , 10)dest = strtol(&source[1] , NULL , 10);忽略第一个字符,因为strtol它停在它遇到的第一个非数字字符

于 2013-10-17T21:57:40.877 回答
2

sscanf怎么样

sscanf( charv1, "%*c%d", &i); //skip the first char then read an integer

http://codepad.org/vOg22G8e

于 2013-10-17T21:58:57.900 回答
1

然后

   int x = atoi(&charv1[1]);
   printf("Here it is as an integer %d\n", x);
于 2013-10-17T21:59:22.843 回答
1

您忘记了每个循环乘以 10。这有效:

        size = (strlen(charv1)-1);
        dec=10;
        for(aux = size; aux > 0; aux--){
            if(aux == (size)){
                v1 = charv1[aux]-'0';
            }
            else{

                aux2 = (charv1[aux]-'0')*dec;
                printf("%d\n", aux2);
                v1 = v1 + aux2;
                dec*=10;
            }
        }
于 2013-10-17T22:00:46.573 回答