Question

In: Computer Science

The following is in C++. The instructions for completion are at the bottom. #include #include #include...

The following is in C++. The instructions for completion are at the bottom.

#include
#include
#include
#include
#include
#include

// function to determine if a token
vector is_token(const string& s) {
}

int main() {
// make this into a loop such that, like a terminal, input is accepted until the user hits CTRL+d
string str;
cout<<">";
getline(cin, str);

//vector to store the strings or characters returned by is_token() function
vector tokens;

tokens = is_token(str);
}

Modify the main() function to loop until the user exits (e.g. by pressing CTRL+d).

Write a function named is_token() that accepts a string of user input and determines what is a token (see below for token determination rules).
The function must return the separated tokens.

Determining if something is a token:

1. Whitespace (space, tab, etc) ends a token and is skipped unless it is in quotes (see below). You will find the function int isspace(char) useful for detecting whitespace characters.
2. Some characters are considered special tokens: | ; < > &. When one of these characters is encountered, the token being built is completed and a new token consisting of the character is created.
3. The character \ is a special character, i.e. an escape character. The next character will be part (or the start) of a token.
4. Items between single or double quotes are treated as parts of the current token.
5. Characters that do not meet the above rules are added on to the current token being built.

Some examples to test your output:

Input: > we\'ll do some "crazy \"air quotes\""
Output (tokens separated by commas): we'll, do, some, crazy "air quotes"

Input: > ls | sort >sorted_files.txt
Output (tokens separated by commas): ls, |, sort, >, sorted_files.txt

Input: > "now\;is"
Output: now;is

Solutions

Expert Solution

Solution:

1.Get the length of input string

2.in a loop, start validating each character of the input string

a.if the character encountered is space , token construction is completed.
      
a1.Remove the '' if any in the current token newly constructed
a2.Add the new token to vector
a3.if charater is encountered is one of |,;,<,>,& , treat them as 1 token and add it to the tokens vector
a4.if it is a normal character other than above, continue constructing the token
a5.if '' is encountered ,add the next character to the current token

3.last token, remove '' if any and add the token to vector
4.Parsing the input string into tokens(as per the requirement) is completed hence return the tokens vector.

output:

Source code:

// stringtokens.cpp : Defines the entry point for the console application.
//

#include<iostream>
#include<vector>
#include<string>
using namespace std;
// function to determine if a token
vector<string> is_token(const string& s)
{
   vector<string> tokens;

   //Get the length of input string

   int nLen = s.length();
  
   //variable to hold each token parsed
   string token;
  
   for(int i=0;i<nLen; i++)
   {
       //if the character encountered is space , token construction is completed.
      
       if (isspace(s[i]))
       {
           //Remove the '' if any
           size_t spos = token.find("\", 0);
           if (spos != string::npos)
           {
               token.replace(spos, 1, "");
           }

           //Add the new token to vector
           tokens.push_back(token);
           token.clear();
       }
       //if charater is encountered is one of |,;,<,>,& , treat them as 1 token and add it to the tokens vector
       else if((s[i] == '|') || (s[i] == ';') || (s[i] == '<') || (s[i] == '>') || (s[i] == '&'))              
       {
           tokens.push_back(token);
           token.clear();
           string temp;
           temp.push_back(s[i]);
           tokens.push_back(temp);
       }
       else //normal character other than above, continue constructing the token
       {
           token.push_back(s[i]);
       }
       //if '' is encountered ,add the next character to the current token
       if (s[i] == '\')
       {
           i++;
           token.push_back(s[i]);
       }
   }

   //last token, remove '' if any and add the token to vector
   size_t spos = token.find("\", 0);
   if (spos != string::npos)
   {
       token.replace(spos, 1, "");
   }

   tokens.push_back(token);

   //return the tokens vector
   return tokens;
}

int main() {
   // loop to get input is accepted until the user hits CTRL+d
   while (true)
   {
       string str;
       cout << "(Ctrl+D) to exit >";
       getline(cin, str);

       //if user pressed Ctrl+D exit out of loop
       if (str.compare("x4") == 0) break;

       //vector to store the strings or characters returned by is_token() function
       vector<string> tokens;

       tokens = is_token(str);

       cout << " Output tokens: ";
       for (int i = 0; i < tokens.size(); i++)
       {
           cout << tokens[i] << " ";
       }
       cout << endl;
   }
}


Related Solutions

Answer the following questions based on the given c file: #include #include #include    int c...
Answer the following questions based on the given c file: #include #include #include    int c = 0; void *fnC() {     int i;     for(i=0;i<10;i++)     {   c++;         printf(" %d", c);     }       } int main() { int rt1, rt2;   pthread_t t1, t2; int trial_count = 0; // For every trial, lets zero out the counter and run the count routine “twice”     // as threads that can be scheduled onto independent cores instead of running     // in sequence. for...
Please complete the following code in C using the comments as instructions. Further instructions are below...
Please complete the following code in C using the comments as instructions. Further instructions are below the code. challenge.c // goal: print the environment variables to the file "env.txt", one per line // (If envp is NULL, the file should be empty, opening in write mode will do that.) // example: // inputs: // envp/environ = {"E1=2","E2=7",NULL} // outputs: // env.txt as a string would be "E1=2\nE2=7\n" // example: // inputs: // envp/environ = {NULL} or NULL // outputs: //...
Revenue Recognition - Percentage of Completion - Project Instructions, Spring 2018 One of your clients is...
Revenue Recognition - Percentage of Completion - Project Instructions, Spring 2018 One of your clients is a large regional construction company. The company has many long-term projects in the works. The spreadsheet you are given contains some information about these jobs. Some of the jobs began last year and continue into the current year, so they exist on both tabs. The projects are in various phases of construction; some of which were completed during the current year. You've been asked...
I need the following C code converted to java or C++ #include <stdio.h> #include <stdlib.h> typedef...
I need the following C code converted to java or C++ #include <stdio.h> #include <stdlib.h> typedef struct node { struct node *left; struct node *right; long data; long leftSize; } node; void btreeInsert(node *new, node **rootptr) { node *parent = NULL, *cursor; /* Find parent */ cursor = *rootptr; while (cursor != NULL) { parent = cursor; if (new->data < cursor->data) { cursor->leftSize += 1; cursor = cursor->left; } else { cursor = cursor->right; } } /* Insert node below...
C CODE PLZ! All instructions for what to do in code #include <stdio.h> int main(int argc,...
C CODE PLZ! All instructions for what to do in code #include <stdio.h> int main(int argc, char **argv) { int n, k, l, r, t, d, i; char str[65]; /* Make the user enter a non-negative integer */ printf("Please enter a non-negative integer: "); scanf("%d", &n); while (n < 0) { printf("Sorry, your input is incorrect.\n"); printf("Please enter a non-negative integer: "); scanf("%d", &n); } /* Convert the integer to reversed binary: e.g. 6 gets converted to 011 */ if...
Complete the following TODO: parts of the code in C++ #include <iostream> #include <string> #include <limits>...
Complete the following TODO: parts of the code in C++ #include <iostream> #include <string> #include <limits> #include <vector> using namespace std; // // CLASS: NODE // class Node{ public: int value = 0; // our node holds an integer Node *next = nullptr; // our node has a pointer to the next Node Node(int i){ // contructor for our Node class value = i; // store a copy of argument "i" in "value" next = nullptr; // be sure next...
C++ CODE ONLY Using the following code. #include <iostream> #include <string> #include <climits> #include <algorithm> using...
C++ CODE ONLY Using the following code. #include <iostream> #include <string> #include <climits> #include <algorithm> using namespace std; // M x N matrix #define M 5 #define N 5 // Naive recursive function to find the minimum cost to reach // cell (m, n) from cell (0, 0) int findMinCost(int cost[M][N], int m, int n) {    // base case    if (n == 0 || m == 0)        return INT_MAX;    // if we're at first cell...
PART II — WORKSHEET COMPLETION Instructions: Complete the partial worksheet presented below, inserting additional labels as...
PART II — WORKSHEET COMPLETION Instructions: Complete the partial worksheet presented below, inserting additional labels as needed AUBREY SERVICES AGENCY Partial Worksheet For the Month Ended April 30, 2012 Account Titles Adjusted Trial Balance Income Statement Balance Sheet Dr. Cr. Dr. Cr. Dr. Cr. Cash      6,500.00 Accounts Receivable      2,000.00 Supplies      3,075.00 Prepaid Insurance      2,000.00 Prepaid Rent         500.00 Equipment    35,000.00 Accum. Depreciation      4,000.00 Notes Payable    14,000.00 Account Payable    12,000.00 Unearned Service Revenue      2,000.00 Salaries and Wages Payable      1,300.00 Interest Payable           50.00...
In C++ Instructions: Use a void function to print the following message (should be in welcome...
In C++ Instructions: Use a void function to print the following message (should be in welcome function) Welcome to the Event Scheduling program create 3 int arrays with 3 positions (one array for days one array for moths and one array for years) (should be in main) Create a file that contains the following (you can just create the file or write the file in the program) 1 / 26 / 2021 12 / 13 / 2020 2 / 1...
Instructions (in C++): 1 ) Use a void function to print the following message (should be...
Instructions (in C++): 1 ) Use a void function to print the following message (should be in welcome function) Welcome to the Event Scheduling program 2 ) create 3 int arrays with 3 positions (one array for days one array for moths and one array for years) (should be in main) 3 ) Create a file that contains the following (you can just create the file or write the file in the program) 1 / 26 / 2021 12 /...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT