2016-10-16 3 views
-3

私はCに新しいです++と私はストリームで作業している間に、私は次のコードを見た:コールdata.readnext(str)が行われはifstream-はistreamと関数呼び出し

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <vector> 
#include <string> 
using namespace std; 

class Results 
{ 
    public: 

     string const& operator[](int index) const 
     { 
      return m_data[index]; 
     } 
     int size() const 
     { 
      return m_data.size(); 
     } 
     void readnext(istream& str) 
     { 
      string line; 
      getline(str, line); 
      cout << "line :" << line <<endl; 

      stringstream lineStream(line); 
      string cell; 

      m_data.clear(); 
      while(getline(lineStream, cell, ',')) 
      { 
       m_data.push_back(cell); 
       cout << cell<<endl; 
      } 

     } 
    private: 
     vector<string> m_data; 
}; 



istream& operator>>(istream& str, Results & data) 
{ 

    data.readnext(str); 
    return str; 
} 



int main() 
{ 
    ifstream file("filename.txt"); 
    Results r1; 
    while(file >> r1) 
    { 
     cout << "1st element: " << r1[3] << "\n"; 
    } 
} 

を引数として渡されますか?私はそれを印刷し、私はアドレスである0x7ffd30f01b10を得る。 2)関数getline(str, line);には、ファイルの最初の行の値を指定します。私は理由を知りません。べきではないということgetline(file, line); 私は、一般的に、これは値がインスタンス化さstd::ifstream fileオブジェクトのstd::istreamスーパークラスへの参照であるので、任意のヘルプは高く評価されるだろう

+0

このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –

+0

書いた人に尋ねてください。 –

答えて

1
  1. どのように機能するかを理解していません。

  2. いいえreadnext()機能の範囲に表示されているfileオブジェクトはありません。コードは正しいです。 strは、readnext()に対するstd::istream &のパラメータであり、最初のパラメータのタイプをstd::getline()に一致させます。

+0

"subobject"はより良いかもしれません –

+0

strはstd :: ifstreamファイルオブジェクトへの参照ですか? –

+0

'str'が宣言されていることを' readnext() '関数のパラメータとして見れば、あなた自身の質問に答えることができます。 –

関連する問題