我是一名C++初學者。我有一個新的項目,我必須學習它,所以我嘗試了一些東西來測試我的理解。對於這個問題,我試圖讀取一個文件,然後在屏幕上打印出來。超級簡單,只是爲了善於理解並理解我正在使用的功能。我將MS Word文檔中的一些文本複製到記事本(* .txt)文件中,並試圖讀取此* .txt文件。 word文檔中的所有文本都以粗體顯示,但除此之外沒有「不尋常」字符。除了加粗的「 - 」符號外,所有內容都會顯示在屏幕上。該字符被打印爲帶有帽子字符的「u」(「所謂的擴展ASCII」代碼150)。我嘗試打印出我的數組中的這個字符的整數值(應該是150),但是我得到了-106。我意識到這個有符號整數與無符號整數150的位數相同。我的問題是如何讓輸出結果爲150?這裏是我的代碼:爲什麼unsigned char *與ifstream :: read一起工作?
#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
所以纔出現「詮釋了」總是讀爲簽署。當我嘗試使「a」無符號時,它將字符的八位左邊的所有位都變爲1。爲什麼是這樣?對不起,問題的長度,只是試圖詳細。謝謝!
那麼有沒有辦法輸出無符號值150?當我嘗試將指針input1聲明爲「unsigned char * input1;」時(正如在原帖中的代碼中所發佈的那樣),我得到一個錯誤,說... :: read'不能將參數1從'unsigned char *'轉換爲'char *'。 – Jade 2010-07-29 17:57:24
是的。使用掩碼:'a3 = input1 [charcheck] & 0xff;'去除符號擴展的一位。然後你的cout將顯示150. – 2010-07-30 05:09:30
好的,謝謝!在這一點上,我對面具一無所知,但現在我有了一個尋找方向。我感謝您的幫助! – Jade 2010-07-30 17:09:27