【问题标题】:Reading bytes from a P6 PPM file into a character array (C++) [duplicate]将 P6 PPM 文件中的字节读入字符数组(C++)[重复]
【发布时间】:2016-05-29 21:43:51
【问题描述】:

以下是相关代码:

string s;
int width, height, max;

// read header
ifstream infile( "file.ppm" );  // open input file
infile >> s; // store "P6"
infile >> width >> height >> max; // store width and height of image
infile.get(); // ignore garbage before bytes start

// read RGBs
int size = width*height*3;
char * temp = new char[size]; // create the array for the byte values to go into
infile.read(temp, size); // fill the array

// print for debugging
int i = 0;
while (i < size) {
    cout << "i is " << i << "; value is " << temp[i] << endl;
    i++;
}

然后,我得到的输出表明数组中的值要么是空白,要么是“?”。我猜这意味着字节没有正确转换为字符?

i 为 0;值是

i 是 1;值是

i 是 2;值是

i 是 3;值是?

i 是 4;值是?

...等等。

【问题讨论】:

  • ASCII 编码不会为 0 到 255 之间的所有值分配可打印字符。
  • "...字节没有转换成字符..."什么意思?
  • @πάνταῥεῖ 我不知道......我真的很困惑。我希望字节在数组中表示为 0 到 255 之间的字符。
  • @user 所以你想看看数字吗?重复的问题可以很好地为您提供所需的答案。
  • 重要提示:您必须以ios::binary 模式打开文件才能安全读取二进制数据。如果不这样做,在 Windows 平台上,由于 CR LF 到 LF 的转换,二进制序列 13 10 将被读取为 10,从而导致颜色分量丢失。

标签: c++ file-io io ppm


【解决方案1】:

看起来您希望它打印一个 BYTE 值,而不是一个字符。试试这个:

cout << "i is " << i << "; value is " << (int)(temp[i]) << endl;

通过将 char 转换为 int,cout 将打印值,而不是 ASCII 码。

【讨论】:

  • 所以我这样做了,现在打印的值是 0、-128 或 -1,这绝对不是它们应该的值。
  • @user:应该是unsigned(temp[i]) 而不是(int)(temp[i])
  • @IInspectable 现在的值都是 0 或 4294967168....
  • @user: 你的数组也需要是unsigned char[size] 类型。
  • @IInspectable 我将初始化更改为“unsigned char temp[size];”。难道我也不需要改变这条线吗? "infile.read((char*)&temp, size*sizeof(temp[0])); // coercion" 因为它不再是 char * 的数组,而只是 char?
猜你喜欢
  • 2016-02-09
  • 1970-01-01
  • 2012-11-08
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多