-7

I try to do a interpreter in c++ and I want to do a function that when the user enter type(a) it will give type of the variable a like a is int or bool or string. So my question is I want to know if the first five letter are type( this is the best solution I think in order to do what I want. But my question is how to do this in another way that I do below because this is a very ugly way !

if (str.at(0) == 't' && str.at(1) == 'y' && str.at(2) == 'p' && str.at(3) == 'e' && str.at(4) == '(' )
Rony Cohen
  • 87
  • 2
  • 14
  • 2
    http://stackoverflow.com/questions/931827/stdstring-comparison-check-whether-string-begins-with-another-string – drescherjm Jan 31 '17 at 21:56

1 Answers1

0

The direct answer to your question is probably using std::string::compare or std::string::find; I suppose a google search with terms "c++ string start with" would have brought you directly to examples with advantages and disadvantages.

However, when writing very simple parsers, the tokenizer strtok from c's string library might me an easier way. strtok subsequently splits a string into tokens, where each call to strtok returns the next token. Characters separating tokens are passed as parameter to strtok:

#include <iostream>
#include<stdio.h>
#include <stdlib.h>

int main()
{

    std::string str = "type(a)";

    if (str.compare(0,5,"type(") == 0) {
        // string starts exactly with `type(`;
        // note: 'type (' would not match...
    }

    char* analyzeStr = strdup(str.c_str());
    char *token = strtok(analyzeStr, "(");
    if (token && strncmp(token, "type", strlen("type")) == 0) {
        // command starts with "type(" or "type  ("
        token = strtok(NULL, ")");
        if (token) {
            // value between brackets
            printf("analyzing type of '%s'", token);
        }
    }
    free(analyzeStr);

    return 0;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • [Read the documentation on strtok](http://en.cppreference.com/w/c/string/byte/strtok) before using it. It comes with a number of caveats stemming from being designed to solve simpler problems in simpler times and may not be suitable. For example note the need to `char* analyzeStr = strdup(str.c_str());` and `free(analyzeStr);` to get around `strtok`'s destructive effects of the source string. – user4581301 Feb 01 '17 at 00:11