2012-05-02 10 views
4

文字列でファイル文字列を読み込むと、>>演算は最初の文字列を取得しますが、 "i"で始まります。最初の文字列が "street"であると仮定すると、 "istreet"のようになります。ファイルからC++を読み込むと、3つの奇妙な文字が入ります

他の文字列は大丈夫です。私は別の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); 
    } 
} 

} 
+2

を*脇*:**ループ条件として '.eofを()'は絶対に使用しないでください。あなたのケースでそうであるように、ほとんど常にバグのコードを生成します。ループ条件で入力操作を行うことをお勧めします。 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

ここでは、別の2つのアイデアがあります。

  1. は、ファイルを1つ作成している場合、彼らと一緒に、彼らの長さを保存し、それらを読むとき、ちょうどこの簡単な計算で、すべての接頭辞をカット:trueFileLength - savedFileLength = numOfByesToCut
  2. は独自の接頭辞を作成しますファイルを保存するとき、そしてそれを検索して、以前に見つけたものをすべて削除するとき。
1

このコードを追加すると、既存のストリームのBOM(Byte Order Mark)がスキップされます。ファイルを開いた後に呼び出します。

// 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. 
} 
関連する問題