Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<fstream>
- #include<stdlib.h>
- #include<string.h>
- #include<ctype.h>
- using namespace std;
- int isKeyword(char buffer[]){
- char keywords[32][10] = {"auto","break","case","char","const","continue","default",
- "do","double","else","enum","extern","float","for","goto",
- "if","int","long","register","return","short","signed",
- "sizeof","static","struct","switch","typedef","union",
- "unsigned","void","volatile","while"};
- int i, flag = 0;
- for(i = 0; i < 32; ++i){
- if(strcmp(keywords[i], buffer) == 0){
- flag = 1;
- break;
- }
- }
- return flag;
- }
- bool isInteger(char* str)
- {
- int i, length = strlen(str);
- if (length == 0)
- return false;
- for (i = 0; i < length; i++) {
- if (str[i] != '0' && str[i] != '1' && str[i] != '2'
- && str[i] != '3' && str[i] != '4' && str[i] != '5'
- && str[i] != '6' && str[i] != '7' && str[i] != '8'
- && str[i] != '9' || (str[i] == '-' && i > 0))
- return false;
- }
- return true;
- }
- bool isRealNumber(char* str)
- {
- int i, length = strlen(str);
- bool hasDecimal = false;
- if (length == 0)
- return false;
- for (i = 0; i < length; i++) {
- if (str[i] != '0' && str[i] != '1' && str[i] != '2'
- && str[i] != '3' && str[i] != '4' && str[i] != '5'
- && str[i] != '6' && str[i] != '7' && str[i] != '8'
- && str[i] != '9' && str[i] != '.' ||
- (str[i] == '-' && i > 0))
- return false;
- if (str[i] == '.')
- hasDecimal = true;
- }
- return hasDecimal;
- }
- int main(){
- char character, buffer[15], operators[] = "+-*/%=";
- ifstream file("compiler.txt");
- int i,j=0;
- if(!file.is_open()){
- cout<<"Can not open the file\n";
- exit(0);
- }
- while(!file.eof()){ // .eof return true when there is no data in the file and return false otherwise
- character = file.get();
- for(i = 0; i < 6; ++i){
- if(character == operators[i])
- cout<<character<<" is operator\n";
- }
- if(isalnum(character)){
- buffer[j++] = character;
- }
- else if((character == ' ' || character == '\n') && (j != 0)){
- buffer[j] = '\0';
- j = 0;
- if(isKeyword(buffer) == 1)
- cout<<buffer<<" is keyword\n";
- else if(isInteger(buffer))
- cout<<buffer<<" is an Integer\n";
- else if(isRealNumber(buffer))
- cout<<buffer<<" is a Real Number\n";
- else
- cout<<buffer<<" is Identifier\n";
- }
- }
- file.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement