Reputation: 3074
I wrote a program to print the hexadecimal values, octal values and the corresponding character, separated by hyphens, for the ASCII values between 40 and 126 (both inclusive). My code is:
#include<iostream>
using namespace std;
int main()
{
int i;
char c;
for(i=40;i<=126;i++)
{
c=i;
cout<<i<<"-"<<hex<<i<<"-"<<oct<<i<<"-"<<c<<"\n";
}
return 0;
}
it works fine but here some values of i
are skiped. i.e 58,59 are not printed. I want to print for all values in 40 to 126 range. Have any suggestions?
Upvotes: 2
Views: 2416
Reputation: 33651
If you want to print first as decimal, you should add std::dec
stream manipulator:
cout << dec << i << "-" << hex << i << "-" << oct << i << "-" << c << "\n";
// ^^^
Because after first loop's iteration, flag std::ios_base::oct
oct` still remains.
Upvotes: 14
Reputation: 137398
Or you can use the good ol' C library:
#include <stdio.h>
int main()
{
int i;
for(i=40;i<=126;i++)
printf("%d 0x%X '%c' \n", i, i, i);
return 0;
}
Upvotes: 0
Reputation: 36630
The last manipulator you used for each call to cout
is oct
, and the stream "remembers" that - so, when you output i
the next time without manipulator, it still uses oct
as output format. Simply use dec
explicitly for the first output of i
:
cout << dec << i << "-" << hex << i << "-" << oct << i << "-" << c <<"\n";
Upvotes: 6