Using Char instead of unsigned to calculate numbers?

How do you use char instead of unsigned to calculate numbers?

This is using char only and nothing else.

Step 1: I ask the user to enter a number.
Step 2: User enters a number.
Step 3: Number user entered is going to be that number squared or cubed or w/e.

For example;
"Enter a number: " 3
" Number you entered multiplied four times: " 81 (Since (3)*(3)*(3)*(3) = 81)


Another example;
"Enter a number: " 5
" Number you entered multiplied four times: " 625 (Since (5)*(5)*(5)*(5) = 625)


Code:
1
2
3
4
Char num;
cout << "Enter a number";
cin >> num;
cout << "Number you entered multiplied four times: " << (num)*(num)*(num)*(num) << endl;  
Last edited on
What do you mean? I'm not really certain as to what your question is exactly. You can treat characters as numbers like you are, but they are only one byte so they can't contain very much.
Last edited on
I added some steps and examples above. I hope it's clear.
Last edited on
operator>> is overloaded for char and char* in order to read characters as ASCII codes.

http://www.cplusplus.com/reference/istream/istream/operator-free/

So you can't read a number into a char directly.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
    char num;
    int tmp;

    std::cout << "Enter a number: ";
    std::cin >> tmp;
    num = tmp;
    std::cout << "num * num * num * num == " << num * num * num * num << std::endl;
}

Soe other points:
char instead of unsigned
On most implementations char is a signed type.
Another example;
"Enter a number: " 5
" Number you entered multiplied four times: " 625 (Since (5)*(5)*(5)*(5) = 625)
As unsigned char have range of 0-255, you will probably get value of 113 (625 % 256)

You can #include <cstdint> and use type uint8_t if you need unsigned byte type
Topic archived. No new replies allowed.