2012-11-06 25 views
3

代码:在C++输出ASCII表

#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; 
    } 
    } 
}; 

输出: enter image description here

为什么我没有得到的值96正确缩进输出和怪异的人物 - 255?

+2

也许通过适当缩进你的代码开始。 –

+10

ASCII表格从0到127. – jrok

+1

请注意,在不使用ASCII的系统上不会打印ASCII。 – chris

回答

6

此行不会做正确的事:

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; 
+0

+1:是的,你知道了。 –

+0

谢谢,修好了! :) –

+0

感谢您的提示,是的,它是有道理从char派生int而不是在输出期间匹配数字和字符值时使用变量i和j。 –

0

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

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

+0

没有解释为什么96-127没有正确输出。 –

+0

@Ryuji:''a''应该是97,所以你的算术在某个地方出了问题。我怀疑,没有超过96的输出是正确的,即使是那些看起来可能的输出。 –

+0

我这个问题,可以在源代码,让我们检查 – Jacek