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

Complete the program used on the instructions given in the comments: C++ lang #include <string> #include...
Complete the program used on the instructions given in the comments: C++ lang #include <string> #include <vector> #include <iostream> #include <fstream> using namespace std; vector<float>GetTheVector(); void main() { vector<int> V; V = GetTheVector(); //reads some lost numbers from the file “data.txt" and places it in //the Vector V Vector<int>W = getAverageOfEveryTwo(V); int printTheNumberOfValues(W) //This should print the number of divisible values by 7 //but not divisible by 3. PrintIntoFile(W); //This prints the values of vector W into an output file...
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: //...
C programming assignment. instructions are given below and please edit this code only. also include screenshot...
C programming assignment. instructions are given below and please edit this code only. also include screenshot of the output //In this assignment, we write code to convert decimal integers into hexadecimal numbers //We pratice using arrays in this assignment #include <stdio.h> #include <stdlib.h> #include <assert.h> //convert the decimal integer d to hexadecimal, the result is stored in hex[] void dec_hex(int d, char hex[]) {    char digits[] ={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',   ...
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...
Please complete the following functions using C. ------------------------------------------------------------ #include #include "dynarray.h" /* * This is the...
Please complete the following functions using C. ------------------------------------------------------------ #include #include "dynarray.h" /* * This is the definition of the dynamic array structure you'll use for your * implementation. Importantly, your dynamic array implementation will store * each data element as a void* value. This will permit data of any type to * be stored in your array. Because each individual element will be stored in * your array as type void*, the data array needs to be an array of...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT