tokenizing issue

I am writing a program for class which takes an expression as input and then prints out the numbers in the expression and the symbols from the expression in order. So for example:

Input:

(5 * 30) + 4

What output should be:

5 30 4 ( * ) +

My output is:

5 3 0 4 ( * ) +

So I have everything figured out except how I should be keeping multiple digit numbers together. Any advice would be greatly appreciated!

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
#include <vector> 
#include <string>
#include <iostream>
#include<cctype>

using namespace std;

int main()
{
	string userIn;
	vector<char> numbers;
	vector<char> symbols;

	cout << "Enter an expression: ";

	getline(cin, userIn);
	
	//Adding each single user input char to a vector 
	vector<char> inputVector(userIn.begin(), userIn.end());

	//Dividing characters by number or symbol and placing them into two separate vectors 
	for (unsigned int i = 0; i < inputVector.size(); i++) {
		if (isdigit(inputVector[i])) {
				numbers.push_back(inputVector[i]);
		} else {
			if (!isspace(inputVector[i])) {
				symbols.push_back(inputVector[i]);
			}
		}
	}
	//Printing characters in number vector
	for (unsigned int i = 0; i < numbers.size(); i++) {
		cout << numbers[i] << " ";
	}

	//Printing elements in symbols vector
	for (unsigned int i = 0; i < numbers.size(); i++) {
		cout << symbols[i] << " ";
	}
	cout << endl;

    return 0;
}

Last edited on
If you look at the loop at line 22, you're doing tokenization character by character, not word by word. That's why you get '3' '0' instead of "30".

Yea that was what I intended to do. Otherwise I am not sure how I would strip the symbols and digits apart.
vector<char> numbers;

The correct direction is :
vector<int> numbers;
closed account (LA48b7Xj)
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
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    cout << "Enter an expression: ";

    string input;
    getline(cin, input);
    stringstream ss {input};

    vector<double> numbers;
    vector<char> symbols;

    for(char ch=ss.get(); ss; ch=ss.get())
    {
        if(isdigit(ch))
        {
            ss.putback(ch);
            double d;
            ss >> d;
            numbers.push_back(d);
        }
        else if(isgraph(ch))
            symbols.push_back(ch);
    }

    for(auto e : numbers)
        cout << e << ' ';

    for(auto e : symbols)
        cout << e << ' ';

    cout << endl;
}
Last edited on
.
Last edited on
Thanks krako! Looks like stringstream was the way to go.
Topic archived. No new replies allowed.