2012-05-09 13 views
3

私はテキストファイルを作成してテキストに一度書き込むことができます。私は新しいファイルを作成せずに、必要なときにそれにもっと多くの行を追加できるようにしたい。私の次の問題は、私が探している出力を得ることができないということです。例えば。 LNAME | |テキストファイルはC++のtxtファイルからデータを取り出す方法

START1
fnameのを含ん| SSN
END1

私の目的は、START1とEND1内のデータを取得し、区切り文字なしFNAMEのLNAMEとSSNを返すだけにあります。ここに私のコードです

int main() 
{ 
    fstream filestr; 
    string line; 

    filestr.open ("file.txt", fstream::in | fstream::out | fstream::app); 
    if(!filestr.is_open()) 
    { 
     cout << "Input file connection failed.\n"; 
     exit(1); 
    } 
    else{ 
     filestr<<"Start2\n"; 
     filestr<< "middle|middle"<<endl; 
     filestr<<"end2"<<endl; 
     if(filestr.good()){ 
      while(getline(filestr, line) && line !="end1"){ 
       if(line !="Start1"){ 
        //below this point the output goes screwy 
        while(getline(filestr, line,'|')){ 
         cout<<"\n"<<line; 
        } 
       } 
      } 
     } 
     filestr.close(); 
    } 

答えて

2

ほぼ:

あなたは、読み取り位置を追加するために、ファイルを開く終わりです。 あなたは読書を始める前に、最初に戻って(あるいは閉じて、もう一度)検索する必要があります。

 filestr.seekg(0); 

二probelemはループが終わりをチェックしませんが、あなたが入れ子になっていることである:

   while(getline(filestr, line,'|')){ 
        cout<<"\n"<<line; 

これは、行を分割します。しかし、それはラインの終わりに止まらない。それはファイルの終わりに達するまで継続します。

  if(line !="Start1") 
      { 
       std::stringstream linestream(line); 
       // ^^^^^^^^^^^^^^^^^^ Add this line 

       while(getline(linestream, line,'|')) 
       {   // ^^^^^^^^^^ use it as the stream 
        cout<<"\n"<<line; 
       } 
      } 

PS:ロキアスタリはで述べたように

start1 
^^^^^ Note not Start1 
1
while(getline(filestr, line)) 
{ 
     if(line !="Start1" && line != "end1") 
     { 
      // Get the tokens from the string.   
     } 
} 
+0

file.txtをであなたは何をすべき

は、現在の行を取得し、独自のストリームとして扱いですポストの下に、filestr.seekg(0);ループスルーする前に必要です。 – Jagannath

関連する問題