lundi 10 février 2020

Converting C to C++

I am very new to both C & C++, my task is to convert a program from C to C++ (Without using any C libraries!). I have done so to the best of my knowledge, but there is one issue. The issue is how would I complete the task without using cstrings (string.h) ? This is probably something simple, but I was unable to it figure out, Thank you!

Part of the program that's using it:

#include <iostream> // Include the I/O library that comes with C++.
//#include <string>
#include <string.h>

#include "scan.h" // Include the local header file.

using namespace std; // State the namespace std, this is used to make the code cleaner and simpler.

char token_image[100];

token scan() {
    static int c = ' '; // next available char; extra (int) width accommodates EOF
    int i = 0; // index into token_image

    /* skip white space */
    while (isspace(c)) {
        c = getchar();
    }
    if (c == EOF)
        return t_eof;
    if (isalpha(c)) {
        do {
            token_image[i++] = c;
            c = getchar();
        } while (isalpha(c) || isdigit(c) || c == '_');
        token_image[i] = '\0';
        if (!strcmp(token_image, "read")) return t_read;
        else if (!strcmp(token_image, "write")) return t_write;
        else return t_id;
    }
    else if (isdigit(c)) {
        do {
            token_image[i++] = c;
            c = getchar();
        } while (isdigit(c));
        token_image[i] = '\0';
        return t_literal;
    } else switch (c) {
        case ':':
            if ((c = getchar()) != '=') {
                cout << stderr << "error\n";
                exit(1);
            } else {
                c = getchar();
                return t_gets;
            }
            break;
        case '+': c = getchar(); return t_add;
        case '-': c = getchar(); return t_sub;
        case '*': c = getchar(); return t_mul;
        case '/': c = getchar(); return t_div;
        case '(': c = getchar(); return t_lparen;
        case ')': c = getchar(); return t_rparen;
        default:
            cout << "error\n";
            exit(1);
    }
}

The header file that is defined is this (if needed):

typedef enum {t_read, t_write, t_id, t_literal, t_gets,
                t_add, t_sub, t_mul, t_div, t_lparen, t_rparen, t_eof} token;

// Define an array and a function that are extern (Visible to the whole program). These are essential to the program.
extern char token_image[100];

extern token scan();

Aucun commentaire:

Enregistrer un commentaire