我有一个让我困惑的简单问题。
目标:我想从文件中读取给定的字节(比如第一个字节)并使用该字节的 ASCII 值生成 int x。因此,例如,如果字节/字符是“a”,我希望 x 为 97(= 十六进制的 61)。我读取文件 example.txt 的第一个字节如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
unsigned int x;
unsigned char b;
ifstream myFile ("example.txt", ios::out | ios::binary);
myFile.seekg (0, ios::beg);
myFile >> b;
x = (unsigned int)b;
cout << hex << x;
return b;
}
问题:如果第一个字节由 08 表示,那么我确实得到 8 的输出。但是如果字节由 09 表示,那么我得到 0。我注意到我似乎获取以下字节,除非该字节也是 09。我不知道我的问题是否仅在字节以 ASCII 表示为 09 时出现。
问题:那么我如何读取文件中的第一个(或第三个或其他)字节并使用该字节的 ASCII 值生成一个 int?
(我在 Windows XP 上)
最佳答案
这应该可以解决它。
myFile >> noskipws >> b;
关于c++ - 如何在 C++ 中读取一个字节并将字节的 ASCII 值保存为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9542519/