为什么unsigned char *不能与ifstream :: read一起使用?

时间:2010-07-29 17:41:34

标签: visual-c++

我是C ++的初学者。我有一个新项目在工作,我必须学习它,所以我正在尝试一些东西只是为了测试我的理解。对于这个问题,我正在尝试读取文件然后在屏幕上打印。超级简单,只是试图擅长它并理解我正在使用的功能。我将MS Word文档中的一些文本复制到记事本(* .txt)文件中,我正在尝试读取此* .txt文件。 word文档中的所有文本都以粗体显示,但除此之外没有“异常”字符。除了粗体“ - ”符号外,所有内容都会在屏幕上打印出来。该字符打印为带有帽子字符的“u”(“所谓的扩展ASCII”代码150)。我尝试在我的数组中打印出这个字符的整数值(应该是150)但是我得到-106。我意识到这个有符号整数与无符号整数150的位数相同。我的问题是如何让输出说150?这是我的代码:

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

       int main() {
       unsigned char* input1;
       int input1size = 57;
       ifstream file("hello_world2.txt",ios::binary | ios::ate);
       if (file.is_open()){
            int size;
            size = (int) file.tellg();
            cout <<"This file is " << size << " bytes." << endl;
            file.seekg(0,ios::beg);
            input1 = new unsigned char[input1size];
            file.read(input1, input1size);
            cout << "The first " << input1size <<" characters of this file are:" << endl<<endl;
            for (int i=0; i<input1size; i++) {
            cout << input1[i];
       }
       cout<<endl;
       }
       else {
       cout <<"Unable to open file" << endl;
       int paus;
       cin>>paus;
       return 0;
       }
       file.close();
       int charcheck = 25;
       int a=0;
       int a1=0;
       int a2=0;
       unsigned int a3=0;
       unsigned short int a4=0;
       short int a5=0;
       a = input1[charcheck];
       a1 = input1[charcheck-1];
       a2 = input1[charcheck+1];
       a3 = input1[charcheck];
       a4 = input1[charcheck];
       a5 = input1[charcheck];
       cout <<endl<<"ASCII code for char in input1[" << charcheck-1 <<"] is: " << a1 << endl;
       cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] is: " << a << endl;
       cout <<endl<<"ASCII code for char in input1[" << charcheck+1 <<"] is: " << a2 << endl;
       cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as unsigned int: " << a3 << endl;
       cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as unsigned short int: " << a4 << endl;
       cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as short int: " << a5 << endl;
       int paus;
       cin>>paus;
       return 0;
       }

所有这些的输出如下:

    This file is 80 bytes.
    The first 57 characters of this file are:

    STATUS REPORT
    PERIOD 01 u 31 JUL 09

    TASK 310: APPLIC

    ASCII code for char in input1[24] is: 32
    ASCII code for char in input1[25] is: -106
    ASCII code for char in input1[26] is: 32
    ASCII code for char in input1[25] as unsigned int: 4294967190
    ASCII code for char in input1[25] as unsigned short int: 65430
    ASCII code for char in input1[25] as short int: -106

因此看起来“int a”始终被视为已签名。当我尝试使“a”无符号时,它将char的8位左边的所有位都变为1。为什么是这样?对不起问题的长度,只是想详细说明。谢谢!

1 个答案:

答案 0 :(得分:0)

你正在处理的是当你将char分配给你的一个时将char提升为int时发生的符号扩展?变量

所有高阶位必须设置为1,以使其与char的较小存储中的负值保持一致。

相关问题