Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I read in a line and delimit it with '!!" in C++?

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, "!!");
like image 675
MyStackFlowethOver Avatar asked Oct 21 '22 01:10

MyStackFlowethOver


2 Answers

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
like image 162
lpapp Avatar answered Oct 24 '22 16:10

lpapp


str.substr(0, inStr.find("!!"));

Example: http://codepad.org/gPoqJ1Ie

Explanation

dmitri explains why the error occurs.

like image 21
Michael Nguyen Avatar answered Oct 24 '22 16:10

Michael Nguyen