Strange results in function

Hi everyone.

I wrote this function to count numbers in an integer but, when I compile and run it, it returns to me strange values. I do not know why.

Here is the code:

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
#include <iostream>

using namespace std;

int digitcount(int n)
{
	int count = 1;
	int temp_n = n;
	while (true)
	{
		temp_n /= 10;
		if (temp_n != 0) ++count;
		if (temp_n == 0) break;
	}

	return count;
}

int main()
{
    int x = 123456;
    int digits = digitcount(x);
    int x1 = x / (10^(digits - 1));    // Should print the 1st digit
    int x2 = x / (10^(digits - 2));    // Should print the 2nd digit
   cout << x1 << "\t" << x2 << digits << endl; 
   
   return 0;
}


Output:

1
2
sh-4.3$ g++ -std=c++11 -o main *.cpp
8230    88186                                   
Last edited on
Hi,

Can you explain what the ^ operator does? This might help to figure out what went wrong.

Also, avoid having line 3, count exists in the std namespace. This might cause confusion where you use that variable.

http://www.cplusplus.com/reference/algorithm/count/


If you remove line 3, put std:: before each std thing.

Try to avoid infinite loops, you have an end condition on line 13
I had an issue with cmath and pow function! I have just found it.

I didn't not about count conflict, I'll change it then!

Thank you very much TheIdeasMan :)
No worries :+)

Do read up about namespaces though, and the various operators. Ideally you should put your own code into it's own namespace/s
Topic archived. No new replies allowed.