Re: Printing non-printable characters
* Alex Vinokur, on 18.05.2011 09:55:
Hi,
// --------------------
#include<iostream>
#include<iomanip>
Add relevant header for 'isprint'.
int main()
{
char data[5];
data[0] = 'a';
data[1] = 5;
data[2] = 'b';
data[3] = 10;
data[4] = 0;
char const data[] = "a\005b\012";
Or thereabouts. It's a long time since I used that silly octal notation. :-)
for (std::size_t i = 0; i< sizeof(data); i++)
for( int i = 0; data[i] != 0; ++i )
{
char ch = data[i];
char const ch = data[i];
if (isprint(static_cast<int>(ch)) != 0)
if( isprint( static_cast<unsigned char>( ch ) ) != 0 )
While the earlier things are mostly style, the type of this cast is important to
avoid Undefined Behavior. If you can guaranteee ASCII only data then it does not
matter, but then you don't need any cast. The correct type is 'unsigned char'
(with a subsequent implicit conversion to 'int').
{
std::cout<< ch;
}
else
{
std::cout<< "\\"<< std::oct<< static_cast<int>(ch)<< std::dec;
}
{
std::cout << ch;
}
else
{
std::cout << "\\" << std::oct << ch+0 << std::dec;
}
Please convert tab characters to spaces before posting.
}
std::cout<< std::endl;
return 0;
}
// ------------------
Output:
a\5b\12\0
Is it possible to get the same or similar output without loop in the
program?
There will be a loop somewhere.
The only question is how indirect and hidden you want it.
In general it's better with explicit code than indirect, hidden, implicit code.
Cheers & hth.,
- Alf
--
blog at <url: http://alfps.wordpress.com>