在C++中输出ASCII表

3

码:

#include <iostream>
#include <iomanip>
using namespace std;

class Ascii_output {
public:
    void run() {
        print_ascii();
    }
private:
    void print_ascii() {
        int i, j;                                                           // i is         used to print the first element of each row
                                                                        // j is used to print subsequent columns of a given row
    char ch;                                                            // ch stores the character which is to be printed
    cout << left;

    for (i = 32; i < 64; i++) {                                         // 33 rows are printed out (64-32+1)
        ch = i;
        if (ch != '\n')                                                 // replaces any newline printouts with a blank character
            cout << setw(3) << i << " " << setw(6) << ch;
        else
            cout << setw(3) << i << " " << setw(6);

        for (j = 1; j < 7; j++) {                                       // decides the amount of columns to be printed out, "j < 7" dictates this
            ch += 32*j;                                                 // offsets the column by a multiple of 32
            if (ch != '\n')                                             // replaces any newline printouts with a blank character
                cout << setw(3) << i+(32*j) << " " << setw(6) << ch;
            else
                cout << setw(3) << i+(32*j) << " " << setw(6);
        }

        cout << endl;
    }
    }
};

输出结果:在这里输入图片描述

为什么我没有得到适当缩进的输出,并且在 96 到 255 的值处出现了奇怪的字符?


2
也许可以先对你的代码进行正确的缩进。 - Lightness Races in Orbit
10
ASCII表从0到127。 - jrok
1
请注意,在不使用ASCII的系统上,这将不会打印出ASCII。 - chris
1
你的代码还有其他问题...字符 a 的 ASCII 码是97,而不是161。我猜这是问题的根源,你打印出一个数字,但大多数情况下并不是该数字对应的正确字母。 - Some programmer dude
3
我建议使用类似 std::isprint 的函数来确保字符是可打印的。例如,ASCII 127 是不可打印的,可能会导致格式错误。 - Some programmer dude
显示剩余5条评论
2个回答

6
这行代码没有做对应该做的事情:

ch += 32*j;

您想按32计数,那么可以选择以下方式:
ch += 32;

或者

ch = i + 32*j;

我强烈建议在输出时使数字和字符值匹配。因此,修改为:
cout << setw(3) << i+(32*j) << " " << setw(6) << ch;

to

cout << setw(3) << int(ch) << " " << setw(6) << ch;

谢谢你的提示,从字符派生int比在输出时使用变量i和j匹配数字和字符值更有意义。 - Petrus K.

0

没有解释为什么96-127没有正确输出。 - Petrus K.
@Ryuji:'a' 应该是在 97,所以你的算术运算有问题。我怀疑所有大于 96 的字符都没有正确输出,即使看起来可能是正确的。 - Lightness Races in Orbit
没错,参考Ben Voigt的答案可以得到正确的解决方案。 - Petrus K.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接