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

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

问题描述:

当我通过字符串从文件字符串中读取时,>>操作获取第一个字符串,但它以“i”开头。假定第一个字符串是“街道”,而不是“is?istreet”。从文件读取C++放入三个奇怪的字符

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

这里是我的代码:

#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); 
    } 
} 

} 
+2

*除了*:** **从不使用'.EOF()'作为一个循环条件。它几乎总是生成错误的代码,就像它在你的情况一样。喜欢在循环条件下进行输入操作:'string word; while(inFile >> word){...}'。 –

你看到一个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; 
} 
+6

另外你可能想提一提他正在读错文件;它应该是'while(inFile >> word)'not'while(!inFile.eof())' –

+0

有没有办法忽略它? – vkx

+0

没问题..... –

这里是另外两个想法。

  1. 如果你是谁创建的文件之一,保存它们的长度与他们一起,和阅读它们时,只是削减所有的前缀,这个简单的计算:trueFileLength - savedFileLength = numOfByesToCut
  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. 
}