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

vkx*_*vkx 4 c++ file-io byte-order-mark

当我通过字符串从文件字符串中读取时,>> operation获取第一个字符串,但它以"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);
    }   
}

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*som 9

您将看到UTF-8 字节订单标记(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;
}
Run Code Online (Sandbox Code Playgroud)

  • 另外你可能想提一下他正在读错文件; 它应该是`while(inFile >> word)`not` while(!inFile.eof())` (6认同)