2012-05-02 118 views
4

當我通過字符串從文件字符串中讀取時,>>操作獲取第一個字符串,但它以「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){...}'。 –

回答

9

你看到一個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

沒問題..... –

0

這裏是另外兩個想法。

  1. 如果你是誰創建的文件之一,保存它們的長度與他們一起,和閱讀它們時,只是削減所有的前綴,這個簡單的計算:trueFileLength - savedFileLength = numOfByesToCut
  2. 創建自己的前綴保存文件時,以及在閱讀搜索文件時刪除所有之前發現的內容。
1

參考上面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. 
}