5

I have tried using getline() but the delimiter being set to "!!" causes the program to not compile. I need it the string read into a string variable called messages. My code looks like this... Help?

cout << "Enter the message> ";
getline(cin, message, "!!");
ksugiarto
  • 940
  • 1
  • 17
  • 40
  • 1
    You cannot use a multiple-character delimiter in `getline` - it takes a delimiter *character* (not a delimiter string), hence the compilation error (a string cannot be used where a char is expected). See [here](http://en.cppreference.com/w/cpp/string/basic_string/getline) for more info - there's no overload that takes a delimiter string. You'll need to either choose a 1-character delimiter instead, or use a different method of handling your input stream. – Mac Sep 13 '13 at 01:51

3 Answers3

2

You are not using the std function properly. You are trying to pass a string for the delimiter rather than a character. If that is the delimiter you need, getline will not help you off-hand.

http://www.cplusplus.com/reference/string/string/getline/

Here you can find a working code for what you would like to achieve:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string message;
    cout << "Enter the message>";
    cin >> message;
    cout << message.substr(0, message.find("!!")) << endl;

    return 0;
}

You need to run this command or something similar for your scenario: g++ main.cpp && a.out

Output is:

Enter the message>sadfsadfdsafsa!!4252435
sadfsadfdsafsa
László Papp
  • 51,870
  • 39
  • 111
  • 135
1
str.substr(0, inStr.find("!!"));

Example: http://codepad.org/gPoqJ1Ie

Explanation

dmitri explains why the error occurs.

Community
  • 1
  • 1
mn.
  • 796
  • 6
  • 12
0

getline() accepts char as delimiter, "!!" is a string

istream& getline (istream& is, string& str, char delim);

That is why your code doesn't compile

  1. Read input char by char and tokenize it yourself. The std::string::find method will be helpful or you may look at boost.tokenizer.
  2. Use '!' as a parameter in getline() or getdelim() to read a string and wait for next '!', continue accumulating the string if not '!'
dmitri
  • 3,183
  • 23
  • 28