oreze
oreze

Reputation: 11

Assign a value to char/unsigned char

How can i assign a value to a char/unsigned char? I tried to do it with this code

#include <iostream>

int main() {
    char a;
    unsigned char b;
    std::cout << "Enter a and b: " << std::endl;
    std::cin >> a >> b;
    std::cout << a << ":" << b << std::endl;
}

but it's printing only first two characters of variable a (i know that char can be one byte value, but i don't know why it doesn't want to accept my number and split it if it's bigger than 9)

Upvotes: 0

Views: 102

Answers (1)

R Sahu
R Sahu

Reputation: 206607

i know that char can be one byte value, but i don't know why it doesn't want to accept my number and split it if it's bigger than 9

There seems to be a misundertanding here.

A char can hold a byte but when you use

std::cin >> a;

only one character is read into a, not the integer value that reprsents a byte.

If your input is 95, only the digit '9', not the integer value 95, is read into a.


Had a been a variable of type int,

std::cin >> a;

would read 95 into a. Of course, then there won't be the need for

std::cin >> a >> b;

That will expect the input for a and the input for b to be separated by one or more whitespace characters.

You can convert the int to a char by simply assigngment or explicit casting.

int i;
char a;
std::cin >> i;  // Provide 95 as input.
a = i;          // a is now the character that corresponds to 95 in the
                // encoding used in your platform.

Upvotes: 5

Related Questions