Help check the code?

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  

#include <iostream>
#include <vector>
#include <string.h>

//add other libraries if needed

using namespace std;


vector<string> split(const string &expression) {
//returns a vector of strings that represent operands or numbers
	vector<string> myvec;
	int length = expression.length();
	int i = 0;
	string elem1;
	string elem2;
	while(i < length)
	{
		if((expression[i] != '*') && (expression[i] != '+'))
		{
			elem1 = elem1 + expression[i];
			i++;
		}
		

		else
		{
			myvec.push_back(elem1);
			elem2 = expression[i];
			myvec.push_back(elem2);
			elem1.clear();
			i++;
		}
	
	}
	myvec.push_back(elem1);

	return myvec;
	
//implement your function here
}

 
int main () {
  //test code 
  //ask the user to enter an expression
  //call the split function
  //display the split items (numbers and operands) on the console
	string exp;
	cout << "Enter an expression: " << endl;
	cin >> exp;

	vector <string> myvec = split(exp);
	for (string s: myvec)
	{
		cout << s << endl;
	}
  //add more test cases if needed

  return 0;
}
If you are going to be using C++ strings include <string>, not <string.h> (<cstring>).

The header you included is for manipulating C string char arrays.

Once you fix that you will run across a problem when extracting a std::string from the input stream with std::cin. If there are any spaces in the user supplied data std::cin extracts only the data up to first space, leaving the rest of the data in the stream.

To extract the entire input, with spaces, use std::getline(), found in the <string> header.

http://www.cplusplus.com/reference/string/string/getline/
Topic archived. No new replies allowed.