为什么打印ascii范围以外的数字?

时间:2013-12-03 08:05:39

标签: c++ ascii

这是我的代码,它将数字作为输入并显示输出的字符

#include <iostream>
#include <stdio.h>
using namespace std;
int A[1000];

int main()
{

    int ln=0,min = 99999999;
    while(!cin.eof())
    {
        A[ln]=0;
        for(int i=0;i<3;++i)
        {
            int x;
            cin>>x;
            A[ln]+=x;
        }
        if(A[ln]<=min)
            min = A[ln];
        ++ln;
    }

    char buffer[2049];
    for(int j=0;j<ln-1;++j)
    {
        int x = A[j] - 250;
        cout<<x<<endl;
        if(x<32)
            cout<<x<<" here goes non-printable ascii"<<endl;
        if(x>127)
            cout<<x<<"here goes non-printable ascii"<<endl;
        buffer[j] = x;
    }

    buffer[ln-1] = 0;
    printf("%s\n",buffer);
}

现在可打印的Ascii值在32到127之间。但是,当我给程序输入296 294 255 268 313 278 311 270 290 305 322 252 276 286 301 305 264 301 251 269 274 311时,我有以下输出,

595
595here goes non-printable ascii
609
609here goes non-printable ascii
621
621here goes non-printable ascii
629
629here goes non-printable ascii
613
613here goes non-printable ascii
620
620here goes non-printable ascii
544
544here goes non-printable ascii
Samuel 

但最后它正在打印“塞缪尔”所以,问题是什么?

2 个答案:

答案 0 :(得分:1)

你打印整数而不是字符。 字符的值在[-128,127]范围内。 unsigned char在[0,255]范围内。在打印之前将整数转换为char或unsigned char。

cout << (char)x << endl;

答案 1 :(得分:1)

因为在对字符串进行类型转换时,仅存储最低有效字节,而595的最低有效字节为1010011,即ASCII 83