0

I am trying to write a getline function that will take in a string of words from an open stream...I have looked on different websites and tried what it says to do, but I am getting tons of weird errors. I need the getline to take in all of the words in the "contents" section of my file. This is what I have tried, but I am getting errors with this.

// Fill a single Tweet from a stream (open file)
// Returns true if able to read a tweet; false if end of file is encountered
// Assumes that each line in the file is correct (no partial tweets)
bool Tweet::FillTweet(ifstream &Din)
{
   string tmp;

   bool Success = false;
   Din >> tmp;
   if (!Din.eof())
   {
      Success = true;
      date = tmp;
      Din >> hashtag >> getline(Din,contents);
   }
   else
      cout << "I don't want to read your tweet anyway. " << endl;
savannaalexis
  • 55
  • 1
  • 1
  • 8

2 Answers2

1

That is the incorrect way to use getline(). Change to:

Din >> hashtag;
getline(Din,contents);

Why? getline() returns a reference to istream. There is no overloaded >> operator that takes two istreams

yizzlez
  • 8,449
  • 4
  • 27
  • 43
1

This

  Din >> hashtag >> getline(Din,contents);

needs to be:

  Din >> hashtag;
  getline(Din, contents);

I would also do

if (Din >> tmp)

instead of if (!Din.eof)

Mats Petersson
  • 119,687
  • 13
  • 121
  • 204
  • Can you explain why you would change if(!Din.eof)? – savannaalexis Apr 17 '14 at 22:51
  • Because you are avoiding an extra check - and you won't get an infinite loop if `date` can't be read but it's not EOF. (Although that is unlikely with a string, of course) – Mats Petersson Apr 17 '14 at 22:54
  • 1
    [Because of this](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Checking your io's instead of assuming they're proper is *always* a good idea. – WhozCraig Apr 17 '14 at 22:55