C++从文件中读取三个奇怪的字符

标签 c++ file-io byte-order-mark

当我逐个字符串地从文件中读取时,>> 操作获取第一个字符串,但它以 "i"开头。假设第一个字符串是“street”,那么它会变成“istreet”。

其他字符串没问题。我尝试了不同的 txt 文件。结果是一样的。第一个字符串以“i”开头。有什么问题?

这是我的代码:

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

int cube(int x){ return (x*x*x);}

int main(){

int maxChar;
int lineLength=0;
int cost=0;

cout<<"Enter the max char per line... : ";
cin>>maxChar;
cout<<endl<<"Max char per line is : "<<maxChar<<endl;

fstream inFile("bla.txt",ios::in);

if (!inFile) {
    cerr << "Unable to open file datafile.txt";
    exit(1);   // call system to stop
}

while(!inFile.eof()) {
    string word;

    inFile >> word;
    cout<<word<<endl;
    cout<<word.length()<<endl;
    if(word.length()+lineLength<=maxChar){
        lineLength +=(word.length()+1);
    }
    else {
        cost+=cube(maxChar-(lineLength-1));
        lineLength=(word.length()+1);
    }   
}

}

最佳答案

您看到的是 UTF-8 Byte Order Mark (BOM) .它是由创建文件的应用程序添加的。

要检测和忽略标记,您可以尝试这个(未经测试的)函数:

bool SkipBOM(std::istream & in)
{
    char test[4] = {0};
    in.read(test, 3);
    if (strcmp(test, "\xEF\xBB\xBF") == 0)
        return true;
    in.seekg(0);
    return false;
}

关于C++从文件中读取三个奇怪的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10417613/

相关文章:

python - 在 Python 中处理 UTF-8 数字

c++ - 无法访问 "Program Files"中的 INI 文件

c++ - 奇怪的错误 C2065 : 'ERROR' : undeclared identifier

c++ - 如何从 C++ 文件中读取以空格分隔的信息

python - 如何确定 CSV 文件的编码?

php - BOM 随机出现在 JSON 回复中

c++ - Circle 类的问题和类成员的打印 vector

c++ - 逐行遍历char数组的最佳方法

Java加载和处理大数据

java - 如何在Java中使用正则表达式解析文本文件并将结果写入另一个文件