I wrote this program in C and now i need to change it to C++.Its quite long, so im not going to put all code in here. I just want to know how to convert it to C++, like the differences between this 2 languages Sorry for the indentation.. i didnt had time to put this code in a good indentation
#include <ctype.h>
#include <string.h>
#include <malloc.h>
#include "lexer.h"
#pragma warning(disable : 4996)
int currentToken;
char *token_ptr;
char token[255];
char *lexer_str; // pointer to the start of the string
int * token_positions;
int n_tokens;
// checks if the first characters of token_ptr are equal to the given string
int firstEqual(char *str)
{
char *tk = token_ptr;
for (;*tk == *str && *tk && *str; tk++, str++);
return *str == '\0';
}
// skips spaces and comments
void skipSpaces()
{
while (*token_ptr && isspace(*token_ptr)) token_ptr++; // skip spaces
if (!*token_ptr)
{
return;
}
if(firstEqual("/*")) // there is a comment here... skip it!
{
token_ptr += 2;
while (*token_ptr && !firstEqual("*/"))
token_ptr++;
token_ptr += 2;
skipSpaces();
}
}
void initLexer(char * str)
{
lexer_str = token_ptr = str;
token_positions = (int *)malloc(sizeof(int) * 1000000); // up to one million tokens
n_tokens = 0;
}
/* adds a new token to the token list */
void addToken(int tk_id, int length)
{
token_positions[n_tokens++] = token_ptr - lexer_str;
currentToken = tk_id;
strncpy(token, token_ptr, length);
token[length] = '\0';
token_ptr += length;
}
int nextToken()
{
skipSpaces();
if (*token_ptr)
{
if (isalpha(*token_ptr)) // a letter
{
// isolate the next token
char * tk_end = token_ptr + 1;
while (*tk_end && (isalnum(*tk_end) || *tk_end == '_')) *tk_end++;
int length = tk_end - token_ptr;
strncpy(token, token_ptr, length);
token[length] = '\0';
// check if is a keyword
if (!strcmp(token, "array"))
{
addToken(TK_ARRAY, length);
}
else if (!strcmp(token, "break"))
{
addToken(TK_BREAK, length);
}
else // not a keyword... must be an id
{
addToken(TK_ID, length);
}
}
else if (isdigit(*token_ptr)) // a digit
{
int length = 0;
while (*token_ptr && isdigit(token_ptr[length])) length++;
addToken(TK_INT, length);
}
else if (*token_ptr == '"') // a string
{
char * tk_end = token_ptr + 1;
while (*tk_end && *tk_end != '"') tk_end++;
int length = tk_end - token_ptr + 1;
addToken(TK_STRING, length);
}
else if (firstEqual(":=")) // an assignment
{
addToken(TK_ASSIGN, 2);
else // no more tokens!
{
currentToken = TK_END_INPUT;
return 0;
}
void prevToken()
{
if (n_tokens > 0)
{
n_tokens--;
token_ptr = lexer_str + token_positions[n_tokens];
}
}
Now i need to convert this 'program' above into C++. Can someone help? Thank you so much
Aucun commentaire:
Enregistrer un commentaire