【问题标题】:outputting ascii table in C++在 C++ 中输出 ascii 表
【发布时间】:2012-11-06 14:01:42
【问题描述】:

代码:

#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 处我没有得到正确缩进的输出和奇怪的字符?

【问题讨论】:

  • 也许从正确缩进代码开始。
  • ASCII 表从 0 到 127。
  • 请注意,这不会在不使用 ASCII 的系统上打印出 ASCII。
  • 您的代码还有其他问题...字符 a 是 ASCII 97,而不是 161。我猜这是您问题的根源,您打印出一个数字,但大多数的时间不是那个数字的正确字母。
  • 我还建议您使用std::isprint 之类的东西来确保字符不可打印。例如,ASCII 127 不可打印,可能会导致您的格式错误。

标签: c++ windows char ascii iostream


【解决方案1】:

这条线没有做正确的事:

ch += 32*j;

你想按 32 来数,要么

ch += 32;

ch = i + 32*j;

我强烈建议您在输出期间使数字值和字符值匹配。所以改变

cout << setw(3) << i+(32*j) << " " << setw(6) << ch;

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

【讨论】:

  • 感谢您的提示,是的,在输出期间匹配数字和字符值时,从 char 派生 int 而不是使用变量 i 和 j 是有意义的。
【解决方案2】:

127 以上的字符不是标准 od ASCII 的一部分。 127 以上的 Windows 中出现的字符取决于所选字体。

http://msdn.microsoft.com/en-us/library/4z4t9ed1%28v=vs.71%29.aspx

【讨论】:

  • 没有解释为什么 96-127 没有正确输出。
  • @Ryuji:'a' 应该是 97,所以你的算法有问题。我怀疑 96 以上的 nothing 是正确输出的,即使是那些看起来可能的输出也是如此。
  • 是的,你是对的,请参阅 Ben Voigts 的答案以获得正确的解决方案。
猜你喜欢
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 2021-12-12
相关资源
最近更新 更多