-2

How is this even possible? One of my textbook questions (studying for an exam here) claim you can do this and ask the following:

Write a function that accepts a string. The function should convert the string to an integral number. If it cannot convert return 0.

Example 1: 8976 returns the value of ((((8*10 + 9) *10)+ 7 )* 10) + 6

Example 2: 67A returns a value of 0

How can this be done? I know you can use the atoi() function but the book wants this to be done without any functions?

Edit: Some further thinking:

 int i, ans;
 char number[5]="8976";

 for(i=0;i<strlen(number);i++)
   ans=(ans*10)+(number[i]-'0');

Would the above work?

10
  • 2
    "How is this even possible?" - Maths
    – user529758
    Jun 24, 2013 at 21:24
  • 1
    Welcome to Stack Overflow. Please read the FAQ soon. There are many functions to do this, including: atoi(); strtol() et al; sscanf(); etc. Jun 24, 2013 at 21:24
  • 3
    Example 1 pretty much tells you how to do it. What remains is to check whether a character is a digit (and handling signs), and check for overflows. In response to your edit: Very close. The checks are still missing. And you haven't initialised ans. Jun 24, 2013 at 21:24
  • 4
    You need to set ans = 0 before you start using it; you probably need to validate that number[i] is a digit. Otherwise, it is about right, though it has no error checking for overflows, negative numbers, explicitly positive numbers (+123), etc. You don't report an error (set ans to zero) for 67A. And using strlen() in the loop like that is sub-optimal; the string length does not change, so add int len = strlen(number); and compare with len instead of strlen(number) in the loop. Jun 24, 2013 at 21:27
  • 2
    Better to use #include <ctype.h> and isdigit((unsigned char)number[i]). Jun 24, 2013 at 21:44

2 Answers 2

3

I was writing something but in the meantime the question was basically answered, in the OP edits and further comments.

Here is the function header:

int f(const char *str)
{

The variables: v is the computed value, c is a pointer to the current character being scanned, d is the value of the current digit.

    int v;
    const char *c;
    int d;

    v = 0;
    c = str;

Iteration will stop on the null terminator, when c points to 0, which is FALSE in C. Scanning is left to right.

    while (*c)
    {

The OP got the main idea right.

        v *= 10;
        d = *c - '0';

You should just test d to check that it is between 0 and 9.

        if (d < 0 || d > 9)
            return 0;

This solution uses pointers in place of indices.

        v += d;
        ++c;
    }

Return the result.

    return v;
}
6
  • Wow. Correctly formatted code. Rare bird on SO. Anyway, I'd suggest making the argument const-correct.
    – user529758
    Jun 24, 2013 at 21:37
  • @darnix911 Perfect, thanks. Also good point with the pointer arithmetic instead of an explicit length and loop counter.
    – user529758
    Jun 24, 2013 at 21:48
  • @user2517940: In case you just started programming, it is a good investment in my opinion to use return (and also break and continue) parsimoniously that is, ideally, only one time at the end of the function. Try to rewrite the function in my answer in a way that it uses a single return v; at the end.
    – damix911
    Jun 24, 2013 at 21:57
  • @darnix911 Not needed, in general. Really not an issue with such a simple function.
    – user529758
    Jun 24, 2013 at 21:59
  • @H2CO3: Thanks, in C++ I never forget const, in C often I do. It must be a trauma from childhood, caused by some esoteric C compiler that didn't support that keyword :-)
    – damix911
    Jun 24, 2013 at 22:00
0

You're halfway there, your code isn't bad just missing a declaration and an if

int main()
{
    int i, ans;
    ans=0;
    char number[5]="12";

    for(i=0;i<strlen(number);i++){
        if( !(number[i]>='0' && number[i]<='9')  ){
            ans = 0;
            break;
        }
        ans=(ans*10)+(number[i]-'0');
    }

    printf("%d\n",ans);

    return 0;
}

you can also check the code here: http://cfiddle.net/cvYCYB

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.