-3

I am new to c++ and while i was working with streams i saw the following code:

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

When the call data.readnext(str) is made: 1)what is the value of str which is passed as an argument? When I print it out and i get 0x7ffd30f01b10 which is an address. 2)in the function getline(str, line); gives line the value of the first row of the file. I don't get why. Shouldn't that be getline(file, line); I generally don't understand how this works so any help would be highly appreciated

nikos_k
  • 49
  • 1
  • 4
  • The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Oct 16 '16 at 13:19
  • Ask the person who wrote it. – Lightness Races in Orbit Oct 16 '16 at 13:37

1 Answers1

1
  1. The value is a reference to the std::istream superclass of the instantiated std::ifstream file object.

  2. No. There is no file object visible in the scope of the readnext() function. The code is correct. str is the std::istream & parameter to readnext(), and matches the type of the first parameter to std::getline().

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148