Pulling my hair out hunting for answers...Now that you have that visual, Here is my question.
I am working on a code where the user enters a letter and it will display both the ascii and hex values. It will loop until 1 is entered.
The problem is, the first time through the output is successful. Once it starts looping, the ascii code is displayed as the hex code. The desired output should be 98 and 99, not 62 and 63, as seen below.
system: Windows 7 on a PC, Using codeblocks with the MINGW compiler.
#include <iostream>
#include <cmath>
usingnamespace std;
int main (void)
{//being main program
char letter, letter1;
bool loop=false;
int asciinum;
do
{//beging enter letter loop
cout << "**To end program enter a 1**\n";
cout << "Please enter a letter to display ASCII and HEX ASCII values for >";
cin >> (letter);
asciinum=letter;
if (letter=='1') loop=true;
else cout << "ASCII " << asciinum <<". \t HEX " << hex<<(int)letter <<".\n"<<endl;
}while (loop==false);//end enter letter loop
return(0);
}//end main program
**To end program enter a 1**
Please enter a letter to display ASCII and HEX ASCII values for >a
ASCII 97. HEX 61.
**To end program enter a 1**
Please enter a letter to display ASCII and HEX ASCII values for >b
ASCII 62. HEX 62.
**To end program enter a 1**
Please enter a letter to display ASCII and HEX ASCII values for >c
ASCII 63. HEX 63.
Welcome to the forums. By doing std::cout << hex; you are setting the base of the entire stream (now and in the future) to hexadecimal. So to print in decimal once again, you need to specify that:
Ah, that's makes sense. I didn't realize the Hex command was switching the entire output to hex, but rather thought it was localized to that single command instance. I was trying instead to put ascii in the same spot to do the same thing. Silly me, dec makes more sense.
Adding dec as you stated did fix the problem--Thank you.
However, adding the static_cast line threw up more errors. Does it require a different library to be included? I am not familiar with C, so I did not recognize the command in that light. Using hex << (int)variable was an example I borrowed from somewhere else through my research to fix the problem.
else cout << "ASCII " << dec<< static_cast<int>asciinum <<". \t HEX " << hex<<(int)letter <<".\n"<<endl;
The errors are: expected '(' before 'asciinum'
invalid operands of types 'int' and 'const char[9]' to binary 'operator<<'
and expected ')' before ';' token.