dunnmifflsys
dunnmifflsys

Reputation: 621

Converting multi-digit char number to int

I'm trying to input a number from the user (like 12345) and turn it into an int. The code I'm using is:

int convertToNumber(char a[10]) {
    int output = 0;
    int b;
    int intArray[10];
    //Finds length
    for (int i = 0; a[i]!=0; i++) {
        if (a[i]==0) {
            b=i-1;
        }
    }
    //Runs through every letter.
    for (int i = 0; a[i]!=0; i++) {
        //Checks if user inputted anything but letter
        intArray[i] = a[i] - '0';
        //Multiplying it by the distance from the end
        intArray[i]= intArray[i] * (10^(b-i));
        //Adds to output
        output=+intArray[i];

    }
    return output;
}

however, this doesn't end up being anything like I hoped it would. Anyone know what's wrong?

Upvotes: 0

Views: 6205

Answers (3)

user529758
user529758

Reputation:

You need an introduction to operators in C++. 10^(b-i) is not 10 to the (b-i)th power, it's 10 XOR b-i. Also, for finding the length, don't roll your own function, use std::strlen().

But you don't need an explicit length anyways: accumulate the product as you go along the string.

int my_str2int(const char *s)
{
    int res = 0;
    while (*s) {
        res *= 10;
        res += *s++ - '0';
    }

    return res;
}

Also, I just noticed the headline:

I'm trying to input a number from the user (like 12345) and turn it into an int

If that's all you want:

long l = std::strtol("12345", NULL, 0);
unsigned long ul = std::strtoul("12345", NULL, 0);
long long ll = std::strtoll("12345", NULL, 0);
unsigned long long ull = std::strtoull("12345", NULL, 0);
int i = std::atoi("12345");

As usually, the docs ain't evil.

Upvotes: 3

SamFisher83
SamFisher83

Reputation: 3995

You want use the pow function in the math library. ^ does xor.

Upvotes: 0

Joe Z
Joe Z

Reputation: 17936

You might try avoiding reinventing the wheel here. Look up strtoul and strtoull to see if they are available on your system. These handle numbers in different bases, too, and will give you a pointer to the first non-digit if your string contained a mixture of digits and non-digits.

And, as others have pointed out, ^ performs bitwise XOR.

Upvotes: 0

Related Questions