C++: Extract Tokens from String using only STL - c++

I want to extract tokens from a given fraction expression, which is passed as a string,
Fraction s("-5 * 7/27");
Where the extracted tokens hold either a single operator or a sequence of digits as an operand, using the stl container only.
May someone guide me to do so? I want to know how to extract the tokens and differentiate the operand from operator, thank you.

Assuming there are always spaces between the tokens, here's how put them all in a queue:
#include <string>
#include <queue>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream formula("-5 * 7/27");
string a_token;
queue<string> tokens;
// Use getline to extract the tokens, and then push them onto the queue.
while (getline(formula, a_token, ' ')) {
tokens.push( a_token );
}
// Print and pop each token.
while (tokens.empty() == false) {
cout << tokens.front() << endl;
tokens.pop();
}
}
Running the program will output:
-5
*
7/27
Now to determine which are operators, numbers, or fractions, you can do something like this in the loop:
if (a_token == "+" || a_token == "-" || a_token == "*" || a_token == "/")
{
// It's an operator
cout << "Operator: " << a_token << endl;
}
else
{
// Else it's a number or a fraction.
// Now try find a slash '/'.
size_t slash_pos = a_token.find('/');
// If we found one, it's a fraction.
if (slash_pos != string::npos) {
// So break it into A / B parts.
// From the start to before the slash.
string A = a_token.substr(0, slash_pos);
// From after the slash to the end.
string B = a_token.substr(slash_pos + 1);
cout << "Fraction: " << A << " over " << B << endl;
}
else
{
// Else it's just a number, not a fraction.
cout << "Number: " << a_token << endl;
}
}
This website: http://www.cplusplus.com/reference/string/string/ will give you information on the string functions.
After modifying the code and running it again, you'll get output like this:
Number: -5
Operator: *
Fraction: 7 over 27

Related

C++ Recursion function

Good afternoon everyone, I am new to recursion and am trying to create a program to take user input to build a math function. It works when doing simple things such as 3 + 4, but when trying something like (3 + 4) + 6 the main prints an empty string. The purpose of the program is to place nested numbers inside parenthesis to make them clear to read. I have tried following the code, but the recursion seems to be what i don't understand. Thanks for your time and help.
Code
#include <iostream>
#include <string>
using namespace std;
string buildEq(bool nested, string tab);
int main()
{
cout << "Welcome to the equation builder!" << endl << endl;
cout << "Each step can only have one operation between two numbers." << endl;
cout << "So the equation (3 + 4) + 6 would have one 'nested' operation." << endl << endl;
string equation = buildEq(false, "");
cout << endl << "The equation you have built is... " << equation << endl;
cout << endl << "Thanks for coming!" << endl;
return 0;
}
string buildEq(bool nested, string tab)
{
string equation;
string nesting;
cout << tab << "For this step, is there nesting? (y/n): ";
cin >> nesting;
if(nesting == "y")
{
nested = true;
tab += "\t";
buildEq(true, tab);
}
else
{
int number = 0;
int operation_count = 1;
while(number < 2)
{
if(nested == true)
{
equation += "(";
}
string num= "";
cout << tab << "What number would you like to enter: ";
cin >> num;
equation += num+= " ";
number++;
while(operation_count == 1)
{
string operation;
cout << tab << "What operation would you like to perform? (+, -, /, *): ";
cin >> operation;
equation += operation += " ";
operation_count++;
}
if(nested == true && number == 2)
{
equation += ")";
}
}
}
return equation;
}
Correct output
Welcome to the equation builder!
Each step can only have one operation between two numbers.
So the equation (3 + 4) + 6 would have one 'nested' operation.
For this step, is there nesting? (y/n): n
What number would you like to enter: 3
What operation would you like to perform? (+, -, /, *): +
What number would you like to enter: 4
The equation you have built is... 3 + 4
Thanks for coming!
Press <RETURN> to close this window...
Function results empty
Welcome to the equation builder!
Each step can only have one operation between two numbers.
So the equation (3 + 4) + 6 would have one 'nested' operation.
For this step, is there nesting? (y/n): y
For this step, is there nesting? (y/n): n
What number would you like to enter: 3
What operation would you like to perform? (+, -, /, *): +
What number would you like to enter: 4
The equation you have built is...
Thanks for coming!
Press <RETURN> to close this window...
(Probably an overkill, but I don't think that the question itself is an easy example for understanding recursions)
In order to understand the recursion part, we need to look at the general problem, and understand how we progress from one invocation to another (the recursive step), and what is our stopping point (the base case) . Your goal here is to create a valid equation, in order to do so, your input should follow certain guidelines. Specifically, in order to verify such a problem, you need to verify that each input is following a syntax which is called Context Free Grammar, denoted by the following rules (N stands for number or nested, O for operation, D for digit and $ for nothing):
N -> ( N ) O | D O
D -> 0-9
O -> + N | - N | * N | / N | $
There are two recursions here. In each stage we need to get a valid equation, and those rules make sure it stays like that.
The following code is creating a proper equation from the user.
Notice a few important notes -
I'm using std::stringstream, which is more efficient at creating strings and appending to the existing "string".
You should not over-use std::endl, since in addition to adding a line break, it also flushes to the stdout, which is expensive.
Using "Using namespace std;" isn't a good habit!
Look at how I pass the same stringstream, and each stage adds to this, in order to create the general string. If your code doesn't add to the "carried" value, it means that you are doing nothing in this recursive step.
The code:
#include <sstream>
#include <iostream>
#include <string>
#include <cctype>
#include <assert.h>
void get_num_or_nested(std::stringstream& eq);
void get_operation_or_stop(std::stringstream& eq);
bool is_number(const std::string& s)
{
int digit_count = 0;
for (const char& character : s)
{
if (std::isdigit(character))
{
++digit_count;
}
}
return !s.empty() && s.size() == digit_count;
}
bool is_operation(char c)
{
return (c == '+' || c == '-' || c == '*' || c == '/');
}
std::string get_input_from_user()
{
std::string input;
std::cin >> input;
return input;
}
void get_operation_or_stop(std::stringstream& eq)
{
std::cout << "Insert one of the following:\n";
std::cout << "An operation - [ + | - | * | / ]\n";
std::cout << "s for Stop" << std::endl;
std::string input = get_input_from_user();
if (input.size() == 1)
{
if (is_operation(input[0]))
{
eq << input;
get_num_or_nested(eq);
}
else if (input != "s")
{
assert(false);
}
// stops!
}
else
{
assert(false);
}
}
void get_num_or_nested(std::stringstream& eq)
{
std::cout << "Insert one of the following:\n";
std::cout << "A number\n";
std::cout << "n for Nested" << std::endl;
std::string input = get_input_from_user();
if (input == "n")
{
eq << "(";
get_num_or_nested(eq);
eq << ")";
get_operation_or_stop(eq);
}
else if (is_number(input))
{
eq << input;
get_operation_or_stop(eq);
}
else
{
assert(false);
}
}
int main()
{
std::cout << "Welcome to the equation builder!\n" << std::endl;
std::stringstream eq;
get_num_or_nested(eq);
std::cout << "The equation you have built is... " << eq.str() << std::endl;
std::cout << "Thanks for coming!" << std::endl;
}
The only thing that is wrong is when the user says yes to nesting. Instead of calling the function and discarding what it returned, you need to return what the function returned.
if(nesting == "y")
{
nested = true;
tab += "\t";
return buildEq(true, tab);
}

c++ count words in array

I need to write a function that gets a string and count how many words there are in the string and how many letters. And then calculate the average of it.
A word in a string is a sequence of letters and numbers separated by one or more spaces.
First of all I have to check if the string is correct. The string must contain only lowercase letters, uppercase letters, and numbers only.
i didnt menage to count all sort of words correctly and also my function doesnt count the last letter.
#include <iostream>
using namespace std;
#include <string.h>
#define SIZE 50
float checkString(char string[]) {
float wordCounter = 0;
float letterCounter = 0;
bool isLegit = true;
int i = 0;
while (isLegit) {
if (((string[i] >= 48 && string[i] <= 57) ||
(string[i] >= 65 && string[i] <= 90) ||
(string[i] >= 97 && string[i] <= 122 ))) {
for (int j = 0; j <= strlen(string); j++) {
if ((string[j - 1] != ' ' && string[j] == ' ' &&
string[i + 1] != ' ')
|| j == (strlen(string) - 1)) {
wordCounter++;
}
else if (string[j] != ' ') {
letterCounter++;
cout << string[j];
}
}
cout << " The avareage is : " << (letterCounter /
wordCounter) << endl;
isLegit = false;
}
else {
return -1;
isLegit = false;
}
}
cout << "Number of words " << wordCounter << endl;
cout << "Number of letters " <<letterCounter << endl;
}
int main() {
char string[SIZE];
cout << "please enter a sentence " << endl;
cin.getline(string, SIZE);
checkString(string);
}
Instead of using char[] for strings, I suggest that you use std::string which can grow and shrink dynamically. It's one of the most common types to use in the standard C++ library. You can also make use of stringstreams which lets you put a string inside it and then you can extract the contents of the stringstream using >>, just like when reading from std::cin.
Example with comments in the code:
#include <iostream>
#include <sstream> // std::stringstream
#include <string> // std::string
// use std::string instead of a char[]
float checkString(const std::string& string) {
// put the string in a stringstream to extract word-by-word
std::istringstream is(string);
unsigned words = 0;
unsigned letters = 0;
std::string word;
// extract one word at a time from the stringstream:
while(is >> word) {
// erase invalid characters:
for(auto it = word.begin(); it != word.end();) {
// Don't use magic numbers. Put the character literals in the code so
// everyone can see what you mean
if((*it>='0' && *it<='9')||(*it>='A' && *it<='Z')||(*it>='a' && *it<='z')) {
// it was a valid char
++it;
} else {
// it was an invalid char, erase it
it = word.erase(it);
}
}
// if the word still has some characters in it, make it count:
if(word.size()) {
++words;
letters += word.size();
std::cout << '\'' << word << "'\n"; // for debugging
}
}
std::cout << "Number of words " << words << "\n";
std::cout << "Number of letters " << letters << "\n";
std::cout << "The average number of letters per word is "
<< static_cast<float>(letters) / words << '\n';
return 0.f; // not sure what you are supposed to return, but since the function
// signature says that you should return a float, you must return a float.
}
int main() {
checkString(" Hello !!! World, now let's see if it works. ");
}
I would like to add an additional answer. This answer is based on "more-modern" C++ and the usage of algorithms. You want to solve 3 tasks:
Check, if string is OK and matched to your expectations
Count the number of words in the given string
Count the number of letters
Calculate the ratio of words/letters
For all this you may use existings algorithms from the C++ standard library. In the attached example code, you will see a one-liner for each task.
The statements are somehow very simple, so that I will not explain much more. If there should be a question, I am happy to answer.
Please see here one possible example code:
#include <iostream>
#include <string>
#include <iterator>
#include <regex>
#include <algorithm>
#include <tuple>
#include <cctype>
std::regex re("\\w+");
std::tuple<bool, int, int, double> checkString(const std::string& str) {
// Check if string consists only of allowed values, spaces or alpha numerical
bool stringOK{ std::all_of(str.begin(), str.end(), [](const char c) { return std::isalnum(c) || std::isspace(c); }) };
// Count the number of words
int numberOfWords{ std::distance(std::sregex_token_iterator(str.begin(),str.end(), re, 1), {}) };
// Count the number of letters
int numberOfLetters{ std::count_if(str.begin(), str.end(), isalnum) };
// Return all calculated values
return std::make_tuple(stringOK, numberOfWords, numberOfLetters, static_cast<double>(numberOfWords)/ numberOfLetters);
}
int main() {
// Ask user to input string
std::cout << "Please enter a sentence:\n";
// Get string from user
if (std::string str{}; std::getline(std::cin, str)) {
// Analyze string
auto [stringOk, numberOfWords, numberOfLetters, ratio] = checkString(str);
// SHow result
std::cout << "\nString content check: " << (stringOk ? "OK" : "NOK") << "\nNumber of words: "
<< numberOfWords << "\nNumber of letters: " << numberOfLetters << "\nRatio: " << ratio << "\n";
}
return 0;
}
Of course there are many more other possible solutions. But, because of the simplicity of this solution, I showed this variant.

Parsing comma-delimited numbers in C++

I have a quick question for everyone. I'm trying to write a simple code to extract numbers form user input and save them to an int array, but I'm having a hard time wrapping my mind around how to make it work. The code shown below works well for single-digit numbers, but not so much for numbers with more than 1 digit.
For instance, if user enters: 1,2,3,4,50,60 here is what I get:
Enter numbers (must be comma delimited): 1,2,3,4,50,60
My numbers are: 12345060
My parsed numbers are: 1
My parsed numbers are: 2
My parsed numbers are: 3
My parsed numbers are: 4
My parsed numbers are: 5
My parsed numbers are: 0
Question: how can I modify this simple piece of code to accurately capture numbers with more than 1 digit? Thanks in advance!!
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
// set up some variables
int numbers[100];
int main() {
// Enter numbers (comma delimited). Ex: 1,2,3,4,50,60<return>
cout << endl << endl << "Enter numbers (must be comma delimited): ";
string nums_in;
getline(cin, nums_in);
nums_in.erase(remove(nums_in.begin(), nums_in.end(), ','), nums_in.end()); // remove the unwanted commas
cout << "My numbers are: " << nums_in << endl;
// convert each char into int
for (int o = 0; o < 6; o++) {
istringstream buf(nums_in.substr(o,1));
buf >> numbers[o];
cout << "My parsed numbers are: " << numbers[o] << endl;
}
cout << endl << endl;
cout << "Done." << endl;
return 0;
}
In your program, you first remove the "unwanted" commas in the input string and then run into the problem that you cannot distinguish the numbers in the input line any more. So it seems as if these commas are not unwanted after all. The solution is to parse the string step by step without removing the commas first, as you need them to split up the input string. Here is an example.
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <vector>
int main() {
// Enter numbers (comma delimited). Ex: 1,2,3,4,50,60<return>
std::cout << std::endl << std::endl << "Enter numbers (must be comma delimited): ";
std::string nums_in;
std::getline(std::cin, nums_in);
// Now parse
std::vector<int> data;
std::istringstream buf(nums_in);
while (!buf.eof()) {
int this_number;
buf >> this_number;
if (buf.bad()) {
std::cerr << "Number formatting error!\n";
return 1;
}
data.push_back(this_number);
char comma = 0;
buf >> comma;
if (!buf.eof()) {
if (buf.fail()) {
std::cerr << "Could not read comma.\n";
return 1;
}
if (comma!=',') {
std::cerr << "Found no comma but '" << comma << "' instead !\n";
return 1;
}
}
}
std::cout << "My numbers are:";
for (auto a : data) {
std::cout << " " << a;
}
std::cout << std::endl;
std::cout << "Done." << std::endl;
return 0;
}
Note that I did not use "using namespace std;" as it is considered to be bad style. Also, I used a C++11 feature for printing out the values and used a vector to store the numbers - in your code, typing in a line with 200 numbers would lead to a crash (or other bad behavior). Finally, the parsing error handling is not yet complete. Making it complete and correct is left as an exercise. An alternative to the istringstream-based approach would be to first split the line by the commas and then to read all numbers separately using istringstreams.
By the way, your question is so practical that it would have been better suited for the standard stackexchange site - the connection to computer science is quite weak.
To solve this kind of problems, you have to write a scanner. The scanner breaks input into tokens. Once you have the ability to break the input into tokens, you can check the order of tokens (see parsers).
In your case you have three tokens: number, comma and end. An example of valid input: number comma number end. Another example: end (empty input). An example of invalid input: number number end (there is no comma between numbers).
Below it is a possible solution to your problem. get_token reads a token from input and stores it in token and number globals. get_numbers reads tokens, checks the syntax and stores the numbers in numbers; the count of numbers is stored in count (also global variables).
#include <iostream>
#include <cctype>
enum { max_count = 100 };
int numbers[max_count];
int count;
enum token_type
{
token_unknwon,
token_end,
token_comma,
token_number
};
token_type token;
int number;
token_type get_token()
{
char c;
// get a character, but skip ws except newline
while ( std::cin.get( c ) && c != '\n' && std::isspace( c ) )
;
if ( ! std::cin || c == '\n' )
return token = token_end;
if ( c == ',' )
return token = token_comma;
if ( std::isdigit( c ) )
{
std::cin.unget();
std::cin >> number;
return token = token_number;
}
return token_unknwon;
}
enum error_type
{
error_ok,
error_number_expected,
error_too_many_numbers,
error_comma_expected
};
int get_numbers()
{
//
if ( get_token() == token_end )
return error_ok; // empty input
while ( true )
{
// number expected
if ( token != token_number )
return error_number_expected;
// store the number
if ( count >= max_count )
return error_too_many_numbers;
numbers[count++] = number;
// this might be the last number
if ( get_token() == token_end )
return error_ok;
// not the last number, comma expected
if ( token != token_comma )
return error_comma_expected;
// prepare next token
get_token();
}
}
int main()
{
//...
switch ( get_numbers() )
{
case error_ok: break;
case error_comma_expected: std::cout << "comma expected"; return -1;
case error_number_expected: std::cout << "number expected"; return -2;
case error_too_many_numbers: std::cout << "too many numbers"; return -3;
}
//
std::cout << count << " number(s): ";
for ( int i = 0; i < count; ++i )
std::cout << numbers[i] << ' ';
//...
return 0;
}
This task can be easily done using std::getline to read the entire line in a string and then parse that string using a std::istringstream to extract the individual numbers and skip the commas.
#include <iostream>
#include <sstream>
#include <vector>
using std::cout;
int main() {
// Enter numbers (comma delimited). Ex: 1,2,3,4,50,60<return>
cout << "\nEnter numbers (must be comma delimited): ";
int x;
std::vector<int> v;
std::string str_in;
// read the whole line then use a stringstream buffer to extract the numbers
std::getline(std::cin, str_in);
std::istringstream str_buf{str_in};
while ( str_buf >> x ) {
v.push_back(x);
// If the next char in input is a comma, extract it. std::ws discards whitespace
if ( ( str_buf >> std::ws).peek() == ',' )
str_buf.ignore();
}
cout << "\nMy parsed numbers are:\n";
for ( int i : v ) {
cout << i << '\n';
}
cout << "\nDone.\n";
return 0;
}
Hm... How about parsing the string without removing the commas? Read the string character for character, placing each character in a temp buffer until you hit a comma, then convert the temp buffer to an int and store it in the vector. Empty the temp buffer and repeat.
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
// set up some variables
vector<int> numbers(0);
int main() {
// Enter numbers (comma delimited). Ex: 1,2,3,4,50,60<return>
cout << endl << endl << "Enter numbers (must be comma delimited): ";
string nums_in;
getline(cin, nums_in);
cout << "My numbers are: " << nums_in << endl;
string s_tmp = "";
int i_tmp;
for(vector<int>::size_type i = 0, len = nums_in.size(); i < len; i++){
if( nums_in[i] == ',' ){
if(s_tmp.size() > 0){
i_tmp = std::stoi(s_tmp);
numbers.push_back(i_tmp);
}
s_tmp = "";
}
else if( i == len-1){
s_tmp += nums_in[i];
i_tmp = std::stoi(s_tmp);
numbers.push_back(i_tmp);
cout << "My parsed numbers are:" << i_tmp << endl;
}
else {
s_tmp += nums_in[i];
}
}
cout << endl << endl;
cout << "Done." << endl;
return 0;
}

Converting from Infix to Postfix using stacks (c++)

I'm currently working on a project to convert from postfix to infix using a stack in the form of a singly linked list. I've managed to convert expressions such as ab+ to (a+b) however when the expression gets longer such as ab+cd*-. It doesn't work. I'm considering pushing the previously converted expression back onto the stack however the stack is of type char and the expression is a string and it complains when I try to push it back. Should I make it a template and if so how would I do it or is there anyway else to solve this problem.
Here is my code:
#include "stack.h"
void convert(string expression){
stack c;
string post = " ";
string rightop = "";
string leftop = "";
string op = "";
for (int i = 0; i <= expression.length(); i++){
c.push(expression[i]);
c.print();
if (expression[i] == '*' ||
expression[i] == '+' ||
expression[i] == '-' ||
expression[i] == '/'){
cout << c.top() << endl;
leftop = c.top();
cout << leftop << endl;
c.pop();
rightop = c.top();
cout << rightop << endl;
c.pop();
op = c.top();
cout << op << endl;
//c.pop();
post = "(" + leftop + " " + op + " " + rightop + ")";
cout << post << endl;
}
//c.push(post);
}
}
int main(){
string expression;
cout << " Enter a Post Fix expression: ";
getline(cin, expression);
convert(expression);
return 0;
}
The original code is lacking following declarations to compile :
#include "stack"
#include "string"
#include "iostream"
using namespace std;
Next, the type of the stack should be a string to be able to store full expressions onto it.
You did not take the elements in proper order from the stack : it is first op, next rightop and finally leftop
The currently commented out last c.pop() is necessary to remove 3rd element from the stack, but it must be followed inside the loop with the (again commented out) c.push(post);
The loop on expression goes one step too far : it should be for (int i =0; i<expression.length();i++) (note the < instead of <=)
When this is done, it is enough to make the convert function to return the last post as a string for the program to give expected result.
As you asked in this other question, it would be much better to ignore spaces in the input string : you should add if (isspace(expression[i])) continue; immediately after the for.
With all those fixes, the code could be :
#include <stack>
#include <string>
#include <iostream>
#include <cctypes>
using namespace std;
string convert(string expression){
stack<string> c;
string post =" ";
string rightop="";
string leftop="";
string op ="";
for (int i =0; i<expression.length();i++){
if (isspace(expression[i])) continue;
c.push(string(expression.c_str() + i, 1));
//c.print();
if(expression[i] == '*' ||
expression[i] == '+' ||
expression[i] == '-' ||
expression[i] == '/'){
cout<<c.top()<<endl;
op=c.top();
cout<<leftop<<endl;
c.pop();
rightop=c.top();
cout<<rightop<<endl;
c.pop();
leftop=c.top();
cout<<op<<endl;
c.pop();
post="(" + leftop + " " + op + " " + rightop + ")";
cout<<post<<endl;
c.push(post);
}
}
return post;
}
int main(){
string expression;
cout<<" Enter a Post Fix expression: ";
getline(cin,expression);
string converted = convert(expression);
cout << "Converted expression : " << converted << endl;
return 0;
}
And when given ab+cd*- you get at the end ((a + b) - (c * d))
You just have to comment out all the traces form convert method ;-)
i get the impression your "stack" is not used properly. e.g. if ab+* is pushed on the stack your variables become leftop = +, rightop = b, op = a, in order to convert a postfix expression it is easiest to create a binary evaluation tree to get the operator precedence right
e.g.
for ab+c* you want
*
/ \
+ c
/ \
a b
and then evaluate the tree either recursively or not. everytime the operator is + or - use parenthesis around it,

How I can manage to keep white space in my String from user input

I'm coding a little console application in C++ and in it I take a string from the user:
cin >> themainstring;
int si = 0;
while (themainstring[si] != '+' || themainstring[si] != '-' ||
themainstring[si] != '*') {
if (themainstring[si] == '+' || themainstring[si] == '-' ||
themainstring[si] == '*') {
lmnopt = themainstring[si];
break; // while
}
si++;
}
int strlenthestring = themainstring.size();
lmnop1 = themainstring.substr(0, si);
lmnop2 = themainstring.substr(si + 1, strlenthestring);
So for example, when I give this input:
ilove+programming
I want to try and cut the string when I see +, - and *. which works fine.
However I want my code to do the same when I input:
ilove + programming (white spaces after and before arithmetical operator)
I have messed around with the WS but I couldn't understand the logic.
Actually the main problem of mine is about C++'s space logic. Why it thinks the space will explode the string input?
I'm not sure I've understood this question completely correctly, however I thought I'd pitch in with some help.
First off, when it comes to looking through strings, C++ has a great set of functions as standard that does that. Point your browser to: Basic String Library.
This contains all the functions you can carry out on a string in C++.
Secondly, something else you need to be aware of, is that you are using std::cin to read user input from the keyboard. By default, cin ignores white spaces, so for example, the following code:
string inputString;
cin >> intputString;
cout << "Input String is: " << inputString << endl;
and let's assume you entered Hello World in as your user input, the program would only output "Hello"
So what you need to do is to use getline. Which allows for whitespaces in your user inputs. And you use it as follows:
std::getline(cin, inputString);
So to give an example where it all gels together:
#include <iostream>
#include <sstream> // for istringstream
#include <string>
using namespace std;
int main(int argc, char * argv[])
{
string inputString;
cout << "Please Enter String: ";
getline(cin, inputString);
cout << "\n" << endl;
cout << "InputString is: " << inputString << endl;
// So you can do something like this
string searchTerm("+");
// Find first of is an operating you can carry out
// on a string so you don't have to use loops.
cout << "Position: " << inputString.find_first_of(searchTerm) << endl;
int pos = inputString.find_first_of(searchTerm);
string part1 = inputString.substr(0, pos);
string part2 = inputString.substr(pos + 1, inputString.length());
cout << "Position of + is " << pos << endl;
cout << "part 1 is: " << part1 << endl;
cout << "part 2 is: " << part2 << endl;
}
Now I know I've only done this with the + sign, but it should serve as a starting point to getting to where you want to be.
Hope all this helps.