【问题标题】:how to prevent istream::get() from reading additional garbage when reading extended ascii values如何防止 istream::get() 在读取扩展 ascii 值时读取额外的垃圾
【发布时间】:2020-03-09 23:06:56
【问题描述】:

例如,在对istream::get() 进行 4 次调用后,我有一个包含 ÀÀ¿¿ 的测试文件,我得到了值(强制转换)值 195、128、195,但我也得到了 -65 -62 之类的值,它们是不在文件中。如何避免这些垃圾值?测试文件包含: ÀÀ¿¿ÀÀ¿¿ÀÀ¿¿ÀÀÀ¿

#include <stdio.h>
#include <vector>
#include <iostream>
#include <string>
#include <math.h>
#include <fstream>
using namespace std;

int main()

    {   
    unsigned int s = 0;
    char c;
    vector<unsigned int> v;


    ifstream is ("test.txt");
    is.seekg(0,is.end);
    int length = is.tellg();
    is.seekg(0,is.beg);
    int i = 0;
    cout<<length<<endl;
    while(i < length/2){
        is.get(c);
        i++;


        cout<<(int)c;
    }


    return 0;
}

【问题讨论】:

  • 您能否使用ideone.com 发布并运行代码(用控制台中的标准输入替换文件输入),以便获得可重现的输出?
  • 我非常怀疑您向我们展示的程序在其输出中同时具有 195 和 -65。在常见的体系结构上,第一个可能在 char 无符号时,第二个在 char 有符号时是可能的。你能给我们一个程序来重现你正在研究的结果或不常见的架构吗?

标签: c++ istream


【解决方案1】:

您的文件很可能包含 Unicode 格式的字符。您在问题文本中包含的特殊字符不是 ASCII 表的一部分。每个 Unicode 字符可以编码为 1 个或多个字节。一次读取一个字节(作为有符号值)可能会产生一个 ASCII 字符(如果存在)或与 Unicode 编码相关的一些其他值。

见: https://en.wikipedia.org/wiki/UTF-8

【讨论】:

  • UTF-8 没有解释输出中同时包含 195 和 -65 的声明结果。
  • 一个有符号的字符不能保存 195,一个无符号的不能保存 -65。
猜你喜欢
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 2016-03-02
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多