4

当我逐个字符串读取文件字符串时,>> 操作获取第一个字符串,但它以 "i" 开头。假设第一个字符串是“street”,而不是“itreet”。

其他字符串没问题。我尝试了不同的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);
    }   
}

}
4

3 回答 3

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;
}
于 2012-05-02T16:13:18.587 回答
2

参考上面 Mark Ransom 的出色回答,添加此代码会跳过现有流上的 BOM(字节顺序标记)。打开文件后调用它。

// Skips the Byte Order Mark (BOM) that defines UTF-8 in some text files.
void SkipBOM(std::ifstream &in)
{
    char test[3] = {0};
    in.read(test, 3);
    if ((unsigned char)test[0] == 0xEF && 
        (unsigned char)test[1] == 0xBB && 
        (unsigned char)test[2] == 0xBF)
    {
        return;
    }
    in.seekg(0);
}

要使用:

ifstream in(path);
SkipBOM(in);
string line;
while (getline(in, line))
{
    // Process lines of input here.
}
于 2013-06-20T16:58:54.313 回答
0

这是另外两个想法。

  1. 如果您是创建文件的人,请将它们的长度与它们一起保存,并且在读取它们时,只需使用以下简单计算删除所有前缀:trueFileLength - savedFileLength = numOfByesToCut
  2. 在保存文件时创建自己的前缀,在阅读时搜索并删除之前找到的所有内容。
于 2012-05-02T16:59:01.650 回答