Abhishek Ghosh
Abhishek Ghosh

Reputation: 2706

How to get sub-strings from a string using two delimiters (; and .) in C++

I have a user input of this kind:

A+B*C;
A*(B+c);
C+F.

Now I want to parse this input and get all sub-strings until the semi-colons and stop scanning when I run into a period symbol.

What is the simplest way to achieve this ?

Also, I have freedom to take input from a file or from the console. Which one would be the easiest to implement ?

I have a method to read from the console as such :

cout << "Enter input: " << endl;
char delimiter = '.';
string inputStr;
getline(cin,inputStr,delimiter);
cout << inputStr;

But if I enter the above mentioned sample input I read only until before period symbol is recieved. So while finding sub strings, what stopping criteria or flag should I take ?

TIA

EDIT:1

Code so far:

#include <string>
#include <iostream>

using namespace std;

int main()
{
    cout << "Enter input: " << endl;
    char delimiter = '.';
    string inputStr;
    getline(cin,inputStr,delimiter);
    cout << inputStr;
    string deli = ';';

    size_t pos = 0;
    string token;
    while ((pos = inputStr.find(deli)) != std::string::npos) {
        token = inputStr.substr(0, pos);
        std::cout << token << std::endl;
        inputStr.erase(0, pos + deli.length());
    }
    std::cout << inputStr << std::endl;
};

ANSWER:

I was wrongly initializing the string deli. I had to do this :

string deli = ";". Instead of single-quotes, I had to use double-quotes, because it a string and not a character! Final working solution here: https://repl.it/EPyC/2

Upvotes: 1

Views: 71

Answers (1)

Saurav Sahu
Saurav Sahu

Reputation: 13924

Use getline with delim ; for all lines. Check for dot(.) for last line.

string line;
while(getline(cin, line, ';')){
    if(line.back() == '.') 
        line.pop_back();
    cout << line <<endl;
}

Upvotes: 1

Related Questions