So my program is taking input from the user, so it's storing it in a string known as x. But I don't want x to take the input after a hard return, it should keep reading until it hits a certain string, let's say "END", so until the user types END, the variable will take everything until that end.

Using getline() you can add a "deliminating character" so that when a CHAR is read, it will stop. i.e. getline(cin, x, 'Q') will keep getting more input until the user types Q followed by a hard return. Is it possible to have a "deliminating string" instead of the character? I already tried it with getline, and it doesn't seem to help.

I need my input to end when the user types "END".
I tried getline(cin, x, "END"), but to no avail.

Appreciate the help once again!

I don't think you are going to find anything pre-written like that with getline or anything else. You want something that both reads in input AND searches for a string at the same time. I don't know of anything like that that exists, and I don't see anything like that with getline. I think you have to read in data, THEN check for the delimiter using "find" from string or something like that. In other words, two separate tasks. One, read in data from the stream. Two, check the stream to see whether you've gone far enough. Possibly step three: Check to see if you've gone "too far" and if so, adjust the string that holds what you've read in and possibly "put back" characters into the stream.

You should probably read a character at a time, then check whether "END" has appeared yet, then continue or stop based on that. There may be something pre-written out there (it comes up a lot, so there probably is), but if it's in the standard libraries, I don't know what it is (which doesn't mean it doesn't exist!).

It would, as VernonDozier suggested, be easy enough to code your own version...

Here's a simple stab at it:

#include <iostream>
#include <string>

std::istream& getline( std::istream& ins, std::string& result, const std::string& terminator )
  {
  char c;
  result.clear();
  while (ins.get( c ))
    {
    result.push_back( c );
    if (result.rfind( terminator ) == (result.length() - terminator.length()))
      {
      result.resize( result.length() - terminator.length() );
      break;
      }
    }
  if (result.length()) ins.clear();
  return ins;
  }

Hope this helps.

This article has been dead for over six months. Start a new discussion instead.