array is not multiplying values?

I'm using a string to get an input of between 2 and 9 integers max. I'm trying to multiply the result of each digit together. For example if I put in 245, the product should be 40. The product however isn't the right number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string x;
	int product = 1;
	int terminate = 0;
	cout << "Please enter a number (minimum 2 digits, maximum 9 digits.)" << endl;
	cout << "(-1 to terminate program)" << endl;
	getline(cin, x);
	while (terminate != -1)
	{
		if (x.length() > 9 || x.length() < 2)
		{
			cout << "You must enter a number between 2 and 9 digits inclusive." << endl;
		}
		else
		{
			for (unsigned int i = 0; i < x.length(); i++)
			{
				product = product * x[i];
			}
			cout << product << endl;
			cout << "Terminate program? (-1 to terminate.) ";
			cin >> terminate;
		}
		return 0;
	}
}
Because when you assigned "x" to a string, that means all integer values you converted from "x" becomes their ASCII integer values.

http://www.asciitable.com/

In other words, if you input in "245", your function would multiply 50, 52, and 53, for the given integer values of those respective ASCII characters.

What you really want to do is have "x" be an int and do modular arithmetic. Like:
1
2
// btw you'll want to write a small numLength function 
int a = x % pow(10, numLength(x)); // this gives you the first digit 


Now all you have to do is assign a few more variables, put that in a for loop, and multiply.



I forgot to mention: the pow(n,n) function comes from the <cmath> library.
Last edited on
I took the input as an integer instead. I solved for the length of the input and put it in a variable.

When I tried putting that variable in the power function like this:

 
int a = x % pow(10, len);


it says " '%': illegal, right operand has type 'double' "
it also says something about unscoped enum type
Last edited on
Oh ok just cast the pow() to an int like: int(pow(a,b))

I forgot that the pow function returns a type double and VS basically takes a dump on itself if you're trying to mod with floats or bigger sized numbers.

Also where are you getting an unscoped enum error?
Topic archived. No new replies allowed.