本关任务:编写程序,以10个字符(每个字符1个字节)为单位,分别按字节方式和字符方式显示一个文件的内容,不能显示的字符用‘.’代替,示例如下:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <cstdio>
#include <iomanip>
#include <cctype>
using namespace std;
void solve(string content)
{
int len = content.size();
for (int off = 0; off < len; off += 10)
{
cout << dec << setw(3) << off << ' ';
for (int i = 0; i < 10 && i + off < len; i++)
{
unsigned char ch = content[i + off];
if (ch < 16)cout << '0';
cout << hex << uppercase << (unsigned int)ch << ' ';
}
// 在这判断是不是最后一行
bool last = off + 10 >= len;
// 最后一行没满
if (last && len % 10 != 0)
{
int lack = off + 10 - len;
for (int i = 0; i < lack; i++)cout << " ";
}
cout << ' ';
for (int i = 0; i < 10 && i + off < len; i++)
{
int ch = content[i + off];
char print = isprint(ch) && ch != ' ' ? char(ch) : '.';
cout << print;
}
cout << endl;
}
}
void loadFile(char *fileName)
{
ifstream in(fileName);
string content;
while(!in.eof())
{
char c = in.get();
if(c == -1)break;
content += c;
}
in.close();
solve(content);
}
int main()
{
char fileName[20];
cin >> fileName;
cout << "Off Bytes Characters" << endl;
cout << "--- ------------------------------ ----------" << endl;
loadFile(fileName);
return 0;
}