Question

In: Computer Science

*****MUST ONLY USE****** #include <iostream> #include <fstream> #include <string.h> #include <stdio.h> Description The word bank system...

*****MUST ONLY USE******
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>


Description

The word bank system maintains all words in a text file named words.txt. Each line in the text file stores a word while all words are kept in an ascending order. You may assume that the word length is less than 20.

The system should support the following three functions:

  • Word lookup: to check whether a given word exists in the word bank.
  • Word insertion: to insert a new word into the word bank. No insertion should be made if the word already appears in the word bank.
  • Word deletion: to delete a word from the word bank.

Please also make sure that

  • After insertion, the order of words in the text file should be kept in ascending order.
  • After deletion, there should not be any empty lines in the text file.
  • After deleting the last word from the system, the system should still keep an empty words.txt.

Implementation

  • Start your coding with the skeleton code and create a text file words.txt next to the C++ file.
  • You don't need to change the function headers.
  • Complete three core functions lookup, insert_word and delete_word.

Expected Output

Below is a sample run of the program. Assume that the file words.txt is empty initially.

1 for lookup; 2 for insertion; 3 for deletion; q for quit: 2
Please enter the word you want to insert: cat
The word "cat" is inserted successfully!

1 for lookup; 2 for insertion; 3 for deletion; q for quit: 2
Please enter the word you want to insert: apple
The word "apple" is inserted successfully!

1 for lookup; 2 for insertion; 3 for deletion; q for quit: 2
Please enter the word you want to insert: dog
The word "dog" is inserted successfully!

1 for lookup; 2 for insertion; 3 for deletion; q for quit: 1
Please enter the word you want to search for: car
The word "car" is not found!

1 for lookup; 2 for insertion; 3 for deletion; q for quit: 1
Please enter the word you want to search for: cat
The word "cat" is found!

1 for lookup; 2 for insertion; 3 for deletion; q for quit: 2
Please enter the word you want to insert: cat
The word "cat" already exists!

1 for lookup; 2 for insertion; 3 for deletion; q for quit: 3
Please enter the word you want to delete: cat
The word "cat" is deleted successfully!

1 for lookup; 2 for insertion; 3 for deletion; q for quit: 3
Please enter the word you want to delete: car
The word "car" is not in the file!
        

Then, below is the expected content of the text file words.txt.

apple
dog
        

Hints

For word insertion and deletion tasks, creating a temporary file may simplify lots of work. This approach is particularly useful if the word bank is large such that you cannot read the whole word bank into memory. For the lab tasks, there are two useful functions for file operation that you may use:

  • rename for renaming a file
  • remove for deleting a file

In addition, we read and manipulate words through char array. The following two functions could be helpful:

  • strcmp for comparing two strings
  • strcpy for copying a string from one char array to another

======================Skeleton Code================================

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>

using namespace std;

#define N 20


// search for a word in the input file, return true if found
bool lookup(const char filename[], const char word[]){
        return false;
}


// delete a word in the input file
// the result should not contain blank lines
void delete_word(const char filename[], const char word[]){
}


// insert a word in the input file such that the words are in ascending order
// it should not insert duplicate word
void insert_word(const char filename[], const char word[]){
}


int main(){

        const char filename[] = "words.txt";
        char choice;
        char word[N];

        while (true){
                cout << "1 for lookup; 2 for insertion; 3 for deletion; q for quit: ";
                cin >> choice;

                if (choice == '1'){
                        cout << "Please enter the word you want to search for: ";
                        cin >> word;
                        if (lookup(filename, word)){
                                cout << "The word \"" << word << "\" is found!" << endl;
                        }else{
                                cout << "The word \"" << word << "\" is not found!" << endl;
                        }
                }else if (choice == '2'){
                        cout << "Please enter the word you want to insert: ";
                        cin >> word;
                        insert_word(filename, word);
                }else if (choice == '3'){
                        cout << "Please enter the word you want to delete: ";
                        cin >> word;
                        delete_word(filename, word);
                }else if (choice == 'q'){
                        break;
                }else{
                        cout << "Invalid input. Please input again." << endl;
                }
                cout << endl;
        }

        return 0;
}

Solutions

Expert Solution

# Only word sorting not implemented

#include<iostream>
#include<fstream>
using namespace std;

int len = 0;

int lookup(string key , string words[]){
  for (int i = 0 ; i < len ; i++){
    if(key == words[i])
      return i;
  }
  return -1;
}

int del(string key , string words[]){
  int a = lookup(key , words);

  if (a == -1)
    return 0;

  for(int i = a ; i < len - 1 ; i++)
    words[i] = words[i+1];
  len--;
  return 1;
}

int insert(string key , string words[]){
  int a = lookup(key , words);
  if( a == -1 ){
    if(len == 0)
    words[len] = key;
    else
     words[len+1] = key; 
    len++;
    return 1;
  }
  return 0;
}

int main(){
  char choice = 'a';
  string key;
  string words[100];
  fstream f;
  f.open("words.txt",ios::out);
  int i = 0;
  while(!f.eof() )
    getline(f , words[i++]);
  f.close();
  len = i;
  do{
    cout << "1.Lookup" << endl;
    cout << "2.Insert" << endl;
    cout << "3.Delete" << endl;
    cout << "q.Quit" << endl;
    cout << "> " ;
    cin >> choice;

    if(choice == '1'){
      cout << "> ";
      cin >> key;
      if(lookup(key , words) != -1)
        cout << "> "<< key << " Found" << endl;
      else
        cout << "> " << key << " Not Found" << endl;
    }

    else if(choice == '2'){
      cout << "> ";
      cin >> key;
      if(insert(key , words))
        cout << "> " << key << " Inserted" << endl;
      else
        cout << "> " << key << " Already present" << endl;
    }
    else if(choice == '3'){
      cout << "> ";
      cin >> key;
      if(del(key, words))
        cout << "> "<< key << " Deleted" << endl;
      else
        cout << "> "<< key << " Not found" << endl;
    }
    else if(choice == 'q'){
      cout << "> "<< "Bye" << endl;
      ofstream f;
      f.open("words.txt");
      for(int i = 0 ; i < len ; i++){
        cout << words[i] << endl;
        f << words[i] << endl;
      }
      f.close();
    }
    else
      cout << "Wrong Choice" << endl;

  }while(choice != 'q');

  return 0;
}

Related Solutions

Use the given Strings.c and Strings.h module: Strings.c: #include "Strings.h" #include <string.h> #include<stdlib.h> #include<stdio.h> char* substring(char*...
Use the given Strings.c and Strings.h module: Strings.c: #include "Strings.h" #include <string.h> #include<stdlib.h> #include<stdio.h> char* substring(char* str, int iPos){ if(iPos > strlen(str)||iPos < 0)return (char*)NULL; char* substr; substr = &str[iPos]; return substr; } int charPosition(char* str, char c){ char* string = (char*)malloc(strlen(str)+1); int i; for(i = 0; i < strlen(str)+1; i++) { if(str[i] == c) { return i; } } return -1; } Strings.h: #include <string.h> /* substring - return a pointer to the substring beginning at the iPos-th position....
#include <iostream> #include <string> #include <fstream> #include <vector> #include <sstream> using namespace std; int main() {...
#include <iostream> #include <string> #include <fstream> #include <vector> #include <sstream> using namespace std; int main() { ifstream infile("worldpop.txt"); vector<pair<string, int>> population_directory; string line; while(getline(infile, line)){ if(line.size()>0){ stringstream ss(line); string country; int population; ss>>country; ss>>population; population_directory.push_back(make_pair(country, population)); } } cout<<"Task 1"<<endl; cout<<"Names of countries with population>=1000,000,000"<<endl; for(int i=0;i<population_directory.size();i++){ if(population_directory[i].second>=1000000000){ cout<<population_directory[i].first<<endl; } } cout<<"Names of countries with population<=1000,000"<<endl; for(int i=0;i<population_directory.size();i++){ if(population_directory[i].second<=1000000){ cout<<population_directory[i].first<<endl; } } } can u pls explain the logic behind this code up to 10 lines pls, many thanks
I get the following errors when I type the code #include <iostream> #include <string.h> #include <bitset>...
I get the following errors when I type the code #include <iostream> #include <string.h> #include <bitset> #include <math.h> #define IS_INTEGRAL(T) typename std::enable_if< std::is_integral<T>::value >::type* = 0 using namespace std; template<class T> std::string inttobits1(T byte, IS_INTEGRAL(T)) { std::bitset<sizeof(T)* CHAR_BIT> bs(byte); return bs.to_string(); } int bitstoint1(string bits) { int value; for (int x = 0, y = bits.length() - 1;x < 8 && x < bits.length();x++) { int val = atoi(bits.substr(y, 1).c_str()); value += (int)val * pow(2, x); } return value; }...
#include <iostream> #include <fstream> #include <string> using namespace std; const int QUIZSIZE = 10; const int...
#include <iostream> #include <fstream> #include <string> using namespace std; const int QUIZSIZE = 10; const int LABSIZE = 10; const int PROJSIZE = 3; const int EXAMSIZE = 3; float getAverage(float arr[], int size) { float total = 0; for (int i = 0; i < size; i++) { total += arr[i]; } return total/size; } // the following main function do.... int main() { ifstream dataIn; string headingLine; string firstName, lastName; float quiz[QUIZSIZE]; float lab[LABSIZE]; float project[PROJSIZE]; float midExam[EXAMSIZE];...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char *argv[]) {     FILE *myFile;...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char *argv[]) {     FILE *myFile;     char fname[20];     //int sum = 0;     int i, j, k, tmp =0;     int num = 0;     int mass = 0;     int count = 0;     int fuel = 0;     int total = 0;     int M[1000];     char ch;     char buffer[32];     printf(" Input the filename to be opened : ");     scanf("%s",fname);     myFile = fopen(fname, "r");     if(myFile == NULL)     {         printf("Can't open file\n");     } while(1)     {         ch =...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char plain[50], cipher[50]="", decrypt[50]=""; int subkeys[50], len;       cout<<"Enter the plain text:"<<endl; cin>>plain;    cout<<"Enter the first subkey:"<<endl; cin>>subkeys[0];    _strupr(plain);    len = strlen(plain);    /**********Find the subkeys**************/    for(int i=1; i<len; i++) { if ((plain[i-1]>='A') && (plain[i-1]<='Z')) { subkeys[i] = plain[i-1]-65; } }    /****************ENCRYPTION***************/       for(int i=0; i<len; i++) { if ((plain[i]>='A') && (plain[i]<='Z')) {    cipher[i] = (((plain[i]-65)+subkeys[i])%26)+65; }...
please fix code #include <stdio.h> #include <stdlib.h> #include <string.h> // function declarations int getValidJerseyNumber(); int getValidRating();...
please fix code #include <stdio.h> #include <stdlib.h> #include <string.h> // function declarations int getValidJerseyNumber(); int getValidRating(); int main() { // declaring variables int size = 5; int jerseyNo[size]; int rating[size]; int i = 0, jno, rate; char option; /* Getting the inputs entered by the user * and populate the values into arrays */ for (i = 0; i < size; i++) { printf("Enter player %d's jersey number:", i + 1); jerseyNo[i] = getValidJerseyNumber(); printf("Enter player %d's rating:\n", i +...
Are my codes correct? #include <iostream> #include <string> #include <cassert> #include <cctype> #include <cstring> #include <stdio.h>...
Are my codes correct? #include <iostream> #include <string> #include <cassert> #include <cctype> #include <cstring> #include <stdio.h> #include <ctype.h> #include<fstream> int locateMinimum( const std::string array[ ], int n ){    if(n <= 0){    return -1;    }    else{    int minInd = 0;    for(int i = 0; i < n; ++i){    if(array[i] < array[minInd]){    minInd = i;    }    }    return minInd;    } } int countPunctuation( const std::string array[], int n) { int...
Add Bubble Sorting & Binary Search Functions to the following code (C++) #include<iostream> #include<fstream> #include<string> #include<iomanip>...
Add Bubble Sorting & Binary Search Functions to the following code (C++) #include<iostream> #include<fstream> #include<string> #include<iomanip> #include<algorithm> using namespace std; const int row = 10; const int col = 7;   ifstream name; ifstream grade; ofstream out; void readData(string stname[row], int stgrade[row][col]); void stsum(int stgrade[row][col], int total[row]); void staverage(int total[row], double average[row]); void stlettergrade(double average[row],char ltrgrade[row]); void displayData(string stname[row], int stgrade[row][col], int total[row], double staverage[row], char ltrgrade[row]); void swapltrgrade(char* xp, char* yp); int main() {    int STG[row][col] = { {0},{0}...
construct c program flow chart #include <stdio.h> #include <math.h> #include <string.h> #define num 6 #define b...
construct c program flow chart #include <stdio.h> #include <math.h> #include <string.h> #define num 6 #define b 6 #define t 6 double bmical(double w, double h){ double o; double bmi; o = pow(h,2); bmi = w/o; return bmi; } double maxheartrate(int num1, int age){ double mhr; mhr = num1 - age; return mhr; } double heartratereserve(double mhr, double rhr){ double hrr; hrr = mhr - rhr; return hrr; } double minrange(int hrr, int rhr){ double mirt; mirt = (hrr * 0.7)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT