If you have the following code:
cout << hex << 10;
The output is 'a', which means the decimal 10 is converted into its hexadecimal value.
However, in the code below...
int n;
cin >> hex >> n;
cout << n << endl;
When input is 12, the output becomes 18. Can anyone explain the details of the conversion? How did it became a decimal value?
I'm interested in the point where it became an int. If broken down, it would be:
(( cin >> hex ) >> n);
Is this correct?
The hex manipulator only controls how a value is read - it is always stored using the same internal binary representation. There is no way for a variable to "remember" that it was input in hex.
"12" in hex is "18" in decimal. When you put in "12" into a hex cin stream, the internal value is 18 decimal. When you output to a stream which is by default decimal, you see the decimal value - "18".
It reads 0x12 (a hex value) and stores it in n, which you then print in decimal. Variables simply contain values, they do not contain information about the base (actually they store everything in base 2).
Related
I hope this is not a naive question. Is type conversion performed implicitly in c++? Because I have asked user to input a number in hexadecimal format, and then when i output that number to the screen without mentioning its format, it is displayed as a decimal format. Am I missing something here?
#include <iostream>
#include <iomanip> using namespace std;
int main() { int number = 0;
cout << "\nEnter a hexadecimal number: " << endl;
cin >> hex >> number;
cout << "Your decimal input: " << number << endl; number;
}
There's no type conversion between hexadecimal and decimal here. Internally your number will be stored in two's complimentary (a binary representation) no matter whether it has been read in as a hex or decimal number. Converting from a string of dec/hex to an integer and the other way around happens when the number is inputted/outputted.
With std::hex you tell the stream you tell the stream to change its default numeric base for integer I/O. Without it, the default is decimal. So if you only do it for std::cin, then it is reading in numbers as hex, but std::cout is still outputting decimal numbers. If you want it to also change its base to hexadecimal, you have to do the same with std::cout:
std::cout << std::hex << "Your hexadecimal input: " << number << std::endl;
I am new to C++ and coming from a C# / Java background I feel like I am kind of spoilt.
What I am trying to achieve here is to get the data input by the user as byte (unsigned char) using cin.
#include <iostream>
using namespace std;
typedef unsigned char byte;
int main()
{
byte num = 0;
char exitKey = '0';
cout << "Type in a number between 0 and 255.\n";
cin >> num;
cout << "\nYour number multiplied by 2 is:\n" << (num * 2);
cin >> exitKey;
return 0;
}
The value returned is the ASCII decimal value of the character I typed in. How can I get the actual value, treating the value as a number?
Help is appreciated. Thanks.
It doesn't matter what type-aliases you use, when reading using cin >> a character is always a character, and will be read as a character.
The value you are getting is the ASCII code for the character '1'.
If you want to read it as a number, then use a proper numeric datatype, like int.
Since you are using char datatype here. The 1 value entered here is considered as character and ASCII value of 1 (49) is getting stored and 49 * 2 = 98 is getting printed.
Instead of char use int as datatype.
Why doesn't the function print "true" when '1' is input for both variables? How can I fix this?
int main() {
int i;
char c;
cout << "Type int: ";
cin >> i;
cout << "Type char: ";
cin >> c;
if (i == (int)c)
cout << "true" << endl;
else
cout << "false" << endl;
}
Even though char is an integer type, it is treated by the >> operator differently from other integer types.
For non-char integer recipient variable the >> operator treats the input as a representation of an integer value. The entire representation is consumed from the input, converted to integer and stored in the recepient variable. For example, if you enter 8 as the input, the recipient variable (say, an int) will receive integer value 8. If you enter 42 as the input, the recipient variable will receive integer value 42.
But for char recipient variable the >> operator treats the input as a mere character sequence. Only the first character of that sequence is consumed and immediately stored in the recipient variable. For example, if you enter 8 as the input, a char recipient variable will receive character '8', which corresponds to integer value of 56. If you enter 42 as the input, the recipient variable will receive character '4', which corresponds to integer value of 52.
That is what leads to the inequality in your case.
Like other input stream objects, std::cin is designed to work differently when you read into different types.
For an int, it reads the numbers you write into the console and parses them into internal integer form. This is convenient: "formatted extraction" means we get a useful int right away and don't need to any conversions from string to number.
For a char, it reads the actual letter or digit or punctuation that you wrote into the console; it does not parse it. It simply stores that character. In this case, c is 49 because that is the ASCII value of '1'.
If you wanted to see whether the int contained 1 and the char contained '1' to match, then you can exploit the property of ASCII that all the digits are found in sequential order starting from 48, or '0':
if (`i` == `c`-'0')
However, if you do this, you should verify that:
Your platform uses ASCII;
c contains a digit ('0', '1', ..., '9').
Generally avoid these hacks if you can. There's usually another way to check your inputs.
char input1;
std::cout << "input1 : ";
std::cin >> input1;
int input2;
std::cout << "input2 : ";
std::cin >> input2;
std::cout << input1 << std::endl;
std::cout << input2 << std::endl;
return 0;
I wrote 'a' at input1 and 'a' at input2.
Ouput is like this.
input1 : a
input2 : a
a
-858993460
I'm curious...'a' charter is 97 in dec. why does it print -858993460?
'a' is not converted to 97 automatically? why?
a, as a string, is not convertible to an int by the rules std::cin follows. Consider this: a is not a valid integer in base 10. std::cin will fail to convert the string "a" to an int.
The reason it prints -858993460 is because the int is not initialized, so it could print anything, or nothing, or do whatever it desires (look up undefined behaviour).
Try something like this instead:
char input2_chr;
std::cin >> input2_chr;
int input2 = input2_chr;
I think the input simply failed, and the value you're seeing is the result of undefined behavior (input2 was never written to).
If you try to read an integer, the character 'a' is not valid so it wouldn't be accepted by the >> operator.
You seem to somehow expect that the input should convert the character to the ASCII code for that character in order to give you the integer-typed result you requested. This reasoning is not supported by the language.
In the first, you asked to input a character, so you got the first
non-whitespace character in the stream. In the second, you asked to
input an integer, so the stream skips whitespace (as it always does with
>>) and attempted to parse an integer. Since "a" cannot be the
start of an integral value, the stream set an error status (the
failbit) and returned, without modifying input2. When you output
the uninitialized variable, you have undefined behavior. (You should
never use a variable you've input without first checking whether the
input succeeded or not.)
From what you describe, it sounds like you are trying to input some
binary format. To do that, you must open the stream in binary mode,
ensure that it is imbued with the "C" locale, and then use
istream::get or istream::read. (Of course, you have to know what
the binary format is that you are reading, in order to be able to
convert the unformatted bytes you read into the actual information you
need.)
As e.g. Aardvard already has answered, you're seeing an arbitrary original value, in the C++ standard called an indeterminate value, because the input operation failed and input2 was not assigned a new value.
To output a decimal representation of the value of a char variable, simply convert it to int in order to direct the output stream to treat as integer.
The easiest way to convert it to int is to encourage an implicit promotion by using the variable in an expression, such as simply adding a + sign in front of it:
#include <iostream>
using namespace std;
int main()
{
char const ch = 'a';
cout << "'" << ch << "' = " << +ch << endl;
}
Output:
'a' = 97
Because you are reading an integer at input2. a isn't an integer. Therefore nothing will be read, and the original value of input2 will be maintained.
In this case, it will be some random value, cause input2 isn't initialized.
You can check whether the read succeeded by checking cin.good()
I need a function that returns the ASCII value of a character, including spaces, tabs, newlines, etc...
On a similar note, what is the function that converts between hexadecimal, decimal, and binary numbers?
char c;
int ascii = (int) c;
s2.data[j]=(char)count;
A char is an integer, no need for conversion functions.
Maybe you are looking for functions that display integers as a string - using hex, binary or decimal representations?
You don't need a function to get the ASCII value -- just convert to an integer by an (implicit) cast:
int x = 'A'; // x = 65
int y = '\t'; // x = 9
To convert a number to hexadecimal or decimal, you can use any of the members of the printf family:
char buffer[32]; // make sure this is big enough!
sprintf(buffer, "%d", 12345); // decimal: buffer is assigned "12345"
sprintf(buffer, "%x", 12345); // hex: buffer is assigned "3039"
There is no built-in function to convert to binary; you'll have to roll your own.
If you want to get the ASCII value of a character in your code, just put the character in quotes
char c = 'a';
You may be confusing internal representation with output. To see what value a character has:
char c = 'A';
cout << c << " has code " << int(c) << endl;
Similarly fo hex valuwes - all numbers are hexadecimal numbers, so it's just a question of output:
int n = 42;
cout << n << " in hex is " << hex << n << endl;
The "hex" in the output statement is a C++ manipulator. There are manipulators for hex and decimal (dec), but unfortunately not for binary.
As far as hex & binary - those are just representations of integers. What you probably want is something like printf("%d",n), and printf("%x",n) - the first prints the decimal, the second the hex version of the same number. Clarify what you are trying to do -