4

In Bjarne Stroustrup's book "Programming Principles and Practices using C++", he is explaining how you can use tokens to stop C++ from automatically using the order of operations on a simple calculator. The code he has given in book does not work - either because of my stupidity, or because I am missing something. I understand that tokens is essentially breaking down lines of code into characters. For example, If I have 5 * 3 there are 3 tokens. Two values and one character. I do not know how to incorporate tokens, or why we should use them. Bjarne's example of a user defined token is this:

class Token {
    public:
        char kind; // what kind of token
        double value; // for numbers - a value
        Token(char ch) // make a token from a char using a constructor
            :kind(ch), value(0) {} // set kind to ch and value to val
        Token(char ch, double val) // make a Token from a char and a double
            :kind(ch), value(val) {}
};

In addition he has provided this example of how you can read input into a vector of tokens:

Token get_token() {} // read a token from cin

vector<Token> tok; // put the tokens in this vector

while(cin >> t5) {
        Token t5 = get_token();
        tok.push_back(t5);
    }
    return 0;

First of all... 1) He prototyped the "get_token()" function but he didn't even write any code for it. 2) Token's object 't5' is getting initialized after it's already getting read in a while loop. 3) I have tried many ways of getting cin to read input into t5, and it is not working. I even defined t5 before the while loop, and I'm getting an invalid operand error for '>>'. This is the first time in this book that I've been utterly stuck. I can't find any examples online of how you can use tokens in C++ to write programs, I only get vague definitions of what a token is. If anyone could assist me in understanding tokens or possibly point me to a good source where I can get a thorough explanation, it would be greatly appreciated.

  • A good thing would be to move on and not bother yourself with this particular example. – Ron Jul 29 '17 at 21:35
  • @Ron The calculator program and improving its efficiency spans an entire chapter of this book. I feel like if I were to simply skip tokens I would get lost in the upcoming pages. –  Jul 29 '17 at 21:41
  • The reason Stroustrop did not supply a "get_token" implementation is that its not very important. You can just assume that somehow the token is read and now you can process it. Its the general idea he's aiming at as opposed to how one reads chars and doubles from a stream per se. I think you can just imagine some implementation exists and carry on. – systemcpro Jul 29 '17 at 21:49

2 Answers2

3

Firstly, Stroustrup is not one of the great teachers, and if you are learning programming you might be better advised starting somewhere other than C++, and somewhere other than his books.

To address your question, a token is a lexical element,and exactly what it is depends on the problem you are addressing. For example, if you are dealing with arithmetic expressions:

100+2/3

then the tokens would be "100", "+", "2", "/" and "3". On the other hand, if you were dealing with English text:

"Here we go again"

then the tokens would probably be:

"Here", "we", "go", "again"

and we simply discard the space characters.

How do you "use tokens"? Well, suppose you want to write a spell-checker - you need to break up the text into words and punctuation (different types of tokens), probably discard most punctuation tokens, and then look up the word tokens in some sort of dictionary.

Louen
  • 3,617
  • 1
  • 29
  • 49
  • I already know Python. I am learning C++ because I believe it is a very powerful language, and I have learned a lot of concepts from it that are both C++-specific and then concepts that can be useful in many languages. –  Jul 29 '17 at 21:39
  • 1
    I agree with everything said except this part: _somewhere other than C++_. Upvoted nevertheless. – Ron Jul 29 '17 at 21:40
  • If you already know Python, you should be familiar with the concept of tokenisation and its uses - as it seems you don't I guess you don't actually know python very well, and haven't written anything significant using it. This would be a mistake - rather than switch to C++ you should consolidate your Python knowledge and write some large, useful programs using it. –  Jul 29 '17 at 21:42
  • @Ron If I should not be learning C++ then what programming language should I be learning? –  Jul 29 '17 at 21:43
  • @Ron I'm strongly of the opinion that everyone should start out learning to program using an interpretive language that naturally supports a REPL. Because that's what I did, and it worked :-) –  Jul 29 '17 at 21:43
  • 1
    @sS5H Quite the opposite. I think you should learn C++ if you want to learn the C++. The [choice of books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) is up for debate. – Ron Jul 29 '17 at 21:44
  • @NeilButterworth You raise a valid point. I was under the impression the OP has some programming experience with other languages. – Ron Jul 29 '17 at 21:48
  • @Ron Well, it seems he does, to some extent. –  Jul 29 '17 at 21:49
  • @NeilButterworth I am familiar with the syntax for Python, C++, and Java but I have not written significant programs other than things like number guessing games and text-based hangman. That's the whole reason why I picked up this book, I want to become more familiar with good programming practices and how I can dissect and construct better code. So far the book has been excellent in giving me a simpler view on programming. –  Jul 29 '17 at 21:52
  • @sSSH Well, not really, or you wouldn't have to ask this question. And the _only_ way you will learn to be a programmer is by writing lots and lots of code, and not code for toy applications like hangman. –  Jul 29 '17 at 21:55
  • @NeilButterworth I am trying to get the general grasp of programming with multiple languages that are similar to each other. I find that I can make connections between languages and see how certain concepts are alike. I'm hardly 16 and I haven't had the chance to take any computer science/computer programming courses yet. As you can tell I am not ready to construct complex and rich software yet, which is particularly why I asked this question. C++ isn't even letting me read input into a token. –  Jul 29 '17 at 22:07
  • 1
    @NeilButterworth Then what is the right way? As I said, the reason I picked up the book is to learn how to work towards the point where I can finally write efficient code. The current chapter I'm trying to read is focused on making code better with the calculator program as its example, but so far my answers have been to skip it or quit C++. –  Jul 29 '17 at 22:18
  • @sSSH I don't believe you have read or understood anything I have posted here (the latter may be my bad, but I can't do any better), so goodbye. –  Jul 29 '17 at 22:25
1

Here you are the answer to your question #1. This is the get_token() function you were asking for!

Here is a link for it below (from Stroustrup's website directly :)):

   Token get_token()    // read a token from cin
    {
        char ch;
        cin >> ch;    // note that >> skips whitespace (space, newline, tab, etc.)

        switch (ch) {
     //not yet   case ';':    // for "print"
     //not yet   case 'q':    // for "quit"
        case '(': case ')': case '+': case '-': case '*': case '/': 
            return Token(ch);        // let each character represent itself
        case '.':
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            {    
                cin.putback(ch);         // put digit back into the input stream
                double val;
                cin >> val;              // read a floating-point number
                return Token('8',val);   // let '8' represent "a number"
            }
        default:
            error("Bad token");
        }
    }
Murphy
  • 3,827
  • 4
  • 21
  • 35
Georgi K.
  • 11
  • 2
  • Thank you for this code snippet, which might provide some limited short-term help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Aug 14 '19 at 16:21