Question

Explain each line of the following code (Briefly) and give an overall reflection on using these...

Explain each line of the following code (Briefly) and give an overall reflection on using these particular functions.

#include<iostream>
#include<string>
using namespace std;
//declare a struct with field mentioned
struct Unit
{
   string unit_code;
   int unit_credict_hrs;
   int unit_semister_study;
   string prerequisites;
   string post_requisites;
   string number_post_requisites;
};
int main()
{
   Unit unit1;
   string str;
   cout << "Enter a tring: ";
   getline(cin, str);
   size_t index = 0;
   string tok,t, del=",";
   string delimit = ";";
   int j = 0,i;
   while ((index = str.find(";")) != std::string::npos)
   {
       tok = str.substr(0, index);
       //std::cout << tok << std::endl;
       str.erase(0, index + delimit.length());
       switch (j)
       {
       case 0:
           unit1.unit_code = tok;
           break;
       case 1:
           unit1.unit_credict_hrs=stoi(tok);
           break;
       case 2:
           unit1.unit_semister_study=stoi(tok);
           break;
       case 3:
           unit1.prerequisites = tok;
          
                  
           if ((i = str.find(del)) != std::string::npos)
           {
              
               t = str.substr(0, i);
               unit1.post_requisites=t;
               str.erase(0, i + del.length());
              
           }
           del = ";";
           if ((i = str.find(del)) != std::string::npos)
           {
                   t = str.substr(0, i);
                   unit1.number_post_requisites = t;
                   str.erase(0, i + del.length());
          
           }
           break;
       }
       ++j;
   }
   //display the structure of unit1
   cout << "Unit Code: " << unit1.unit_code << endl;
   cout << "Unit credit code: " << unit1.unit_credict_hrs << endl;
   cout << "Unit semister code: " << unit1.unit_semister_study << endl;
   cout << "Unit prerequisites: " << unit1.prerequisites << endl;
   cout << "Unit post_requisites: " << unit1.post_requisites << endl;
   cout << "Unit number of post requisites: " << unit1.number_post_requisites << endl;
}

=====================================================
/*Output
Enter a tring: 123MAT;3;2; 147MAT; 159MAT, 146MAT;
Unit Code: 123MAT
Unit credit code: 3
Unit semister code: 2
Unit prerequisites: 147MAT
Unit post_requisites: 159MAT
Unit number of post requisites: 146MAT
*/

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<iostream> : It includes iostream header file to use in the program.


#include<string> : It includes string header file to use in the program.


using namespace std; : It is used to avoid writing std:: when using cin,cout etc(cout instead of std::cout)


//declare a struct with field mentioned
struct Unit : Name of structure is unit
{ // Starting of structure definition
   string unit_code; : unit_code is a structure variable of type string to store value seperated from the input string


   int unit_credict_hrs; : integer type variable to store credit hours seperated from the input string


   int unit_semister_study; : It stores integer type data to represent semester study seperated from the input string


   string prerequisites; : It stores prerequisties needed of type string


   string post_requisites; : It stores prerequesties needed of type string


   string number_post_requisites; //Used to stores unit number of post requesties


}; //End of structure defintion

int main() //Main program starts from here , it returns an integer value


{ // Execution of program begins from here


   Unit unit1; // unit1 is a variable declared using structure type Unit,it has access to all variables declared under the structure Unit
   string str; // str is string variable to store strings,it holds input data given by user (eg : 123MAT;3;2; 147MAT; 159MAT, 146MAT; )


   cout << "Enter a string: "; //Display the message "Enter a string"


   getline(cin, str); //Get a line of string from user input and stores to variable str for future reference


   size_t index = 0; //size_t represents size of any object in bytes, here index = 0 bytes


   string tok,t, del=","; // Assigns ' , ' to tok,t,del variables of type string


   string delimit = ";"; //A delimiter ' ; ' is used to split the input string


   int j = 0,i; // j is used in the switch case to store each value seperated by delimiter to strucutre variables members such as ' unit_code ' etc..

// i stores the position in index returned by the find() method .


   while ((index = str.find(";")) != std::string::npos) // index=str.find(";") assigns the position of delimiter ' ; ' returned by find method

// std::string::npos , means end of string as an index value

// index = str.find(";")) != std::string::npos , check whether  the position of ' ; ' is not the end of string.
   { //While begins here


       tok = str.substr(0, index); //tok is assigned the portion of string in 'str' starting from index ' 0 ' to the position upto where ' ; ' is found(index stores the position where the ' ; ' is found)

//Initial case tok="123MAT"


       //std::cout << tok << std::endl; //A comment , that will not execute

// endl is used to print a newline


       str.erase(0, index + delimit.length()); //str.erase(pos1,pos2) ,it erases the string from positions pos1 to pos2 stored in ' str ' and restore the remaining to ' str '

//str.erase(0,index+delimit.length()) means

//str.erase(0,5+1) in intial case

//Now ' str ' becomes " 3;2; 147MAT; 159MAT, 146MAT; "
       switch (j)

//A switch case is used to store the seperated data to its corresponding variables
       {
       case 0:
           unit1.unit_code = tok;
//unit1.unit_code is used to access the structure member variable

//unit1.unit_code="123MAT"


           break; //To terminate a case


       case 1:


           unit1.unit_credict_hrs=stoi(tok); // stoi(tok) converts a string to number if possible

//unit1.unit_credict_hrs has value 3
           break;
       case 2:
           unit1.unit_semister_study=stoi(tok);
//unit1.unit_semister_study has value 2
           break;
       case 3:
           unit1.prerequisites = tok;
//unit1.prerequisites has value 147MAT
          
// here str ="159MAT, 146MAT;"
           if ((i = str.find(del)) != std::string::npos) //Check whether position of ' , ' not equal to end of the string,i = position of ' , ' , i.e. i =6
           {
              
               t = str.substr(0, i);
// t = str.substr(0,6) ,i.e. t ="159MAT"


               unit1.post_requisites=t; //unit1.post_requisites = "159MAT"


               str.erase(0, i + del.length()); // here str becomes " 146MAT; "
              
           }
           del = ";";
// here del is assigned ' ; ' by replacing ' , ' to seperate the last value "146MAT"


           if ((i = str.find(del)) != std::string::npos) //here i=6 which is not equal to end of string

//A string is terminated by a null character ' \0 '
           {
                   t = str.substr(0, i);
// t has the value "146MAT"


                   unit1.number_post_requisites = t; //unit1.number_post_requisites has value "146MAT"


                   str.erase(0, i + del.length()); //erase the part of string from index value 0 to i + del.length() ,i.e. 0 to 7.

//Now finally the string ' str ' is empty,all the values are seperated and stored in corresponding variables.
          
           }
           break;
       }
       ++j;
//j value is pre-incremented each time to goto next case of switch,++j = j=j+1
   }
   //display the structure of unit1

//Display the values seperated and stored in corresponding variables.

//endl is used to begin with a newline


   cout << "Unit Code: " << unit1.unit_code << endl;
   cout << "Unit credit code: " << unit1.unit_credict_hrs << endl;
   cout << "Unit semister code: " << unit1.unit_semister_study << endl;
   cout << "Unit prerequisites: " << unit1.prerequisites << endl;
   cout << "Unit post_requisites: " << unit1.post_requisites << endl;
   cout << "Unit number of post requisites: " << unit1.number_post_requisites << endl;
}

This program is used to seperate the value from the string entered by the user and store the seperated value to its corresponding variables defined in the structure that can be accessed by the structure variable ' unit1 '.Here a seperate a value we mainly use a ' ; '.

Thus we get the output as :

Enter a string: 123MAT;3;2; 147MAT; 159MAT, 146MAT;
Unit Code: 123MAT
Unit credit code: 3
Unit semister code: 2
Unit prerequisites: 147MAT
Unit post_requisites: 159MAT
Unit number of post requisites: 146MAT

Add a comment
Know the answer?
Add Answer to:
Explain each line of the following code (Briefly) and give an overall reflection on using these...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The provided code is my solution, stripped of the details needed to make it work. It...

    The provided code is my solution, stripped of the details needed to make it work. It is not a “good” program. It lives in a single file, does not use classes, and it has those evil global variables. That is by design. I want to to craft code. Use my code as a guide to help you put together the needed parts. #include #include #include // defaults const int MAX_STEPS = 100; // how long do we run the simulation...

  • ***************Fix code recursive function #include <iostream> #include <cctype> #include <string> using namespace std; void printUsageInfo(string executableName)...

    ***************Fix code recursive function #include <iostream> #include <cctype> #include <string> using namespace std; void printUsageInfo(string executableName) { cout << "Usage: " << executableName << " [-c] [-s] string ... " << endl; cout << " -c: turn on case sensitivity" << endl; cout << " -s: turn off ignoring spaces" << endl; exit(1); //prints program usage message in case no strings were found at command line } string tolower(string str) { for(unsigned int i = 0; i < str.length(); i++)...

  • #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str);...

    #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str); int numConsonants(char *str); int main() {    char string[100];    char inputChoice, choice[2];    int vowelTotal, consonantTotal;    //Input a string    cout << "Enter a string: " << endl;    cin.getline(string, 100);       do    {        //Displays the Menu        cout << "   (A) Count the number of vowels in the string"<<endl;        cout << "   (B) Count...

  • #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str);...

    #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str); int numConsonants(char *str); int main() {    char string[100];    char inputChoice, choice[2];    int vowelTotal, consonantTotal;    //Input a string    cout << "Enter a string: " << endl;    cin.getline(string, 100);       do    {        //Displays the Menu        cout << "   (A) Count the number of vowels in the string"<<endl;        cout << "   (B) Count...

  • I need help with this code. I'm using C++ and Myprogramming lab to execute it. 11.7:...

    I need help with this code. I'm using C++ and Myprogramming lab to execute it. 11.7: Customer Accounts Write a program that uses a structure to store the following data about a customer account:      Customer name      Customer address      City      State      ZIP code      Telephone      Account balance      Date of last payment The program should use an array of at least 20 structures. It should let the user enter data into the array, change the contents of any element, and display all the...

  • #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; struct transition{ // transition structure...

    #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; struct transition{ // transition structure char start_state, to_state; char symbol_read; }; void read_DFA(struct transition *t, char *f, int &final_states, int &transitions){ int i, j, count = 0; ifstream dfa_file; string line; stringstream ss; dfa_file.open("dfa.txt"); getline(dfa_file, line); // reading final states for(i = 0; i < line.length(); i++){ if(line[i] >= '0' && line[i] <= '9') f[count++] = line[i]; } final_states = count; // total number of final states // reading...

  • can you please split this program into .h and .cpp file #include <iostream> #include<string> #include<fstream> #define...

    can you please split this program into .h and .cpp file #include <iostream> #include<string> #include<fstream> #define SIZE 100 using namespace std; //declare struct struct word_block {    std::string word;    int count; }; int getIndex(word_block arr[], int n, string s); int main(int argc, char **argv) {    string filename="input.txt";    //declare array of struct word_block    word_block arr[SIZE];    int count = 0;    if (argc < 2)    {        cout << "Usage: " << argv[0] << "...

  • c++ Consider the following statement string str "Now is the time for the party!" What is...

    c++ Consider the following statement string str "Now is the time for the party!" What is the output of the following statements? (Assume that all parts are independent of each other.) a. cout <str·size ( ) end 1 ; b. Cout << str. substr (7, 8) <<endl: c. string: :size type indstr.find'£') string s str. substr (ind 4, 9); d. cout << str insert (11,"best " <<endl e. str.erase (16, 14) str.insert (16, "to study for the exam? ") cout...

  • fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string>...

    fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; struct book { int ISBN; string Author; string Title; string publisher; int Quantity; double price; }; void choice1(book books[], int& size, int MAX_SIZE) { ifstream inFile; inFile.open("inventory.txt"); if (inFile.fail()) cout <<"file could not open"<<endl; string str;    while(inFile && size < MAX_SIZE) { getline(inFile, str); books[size].ISBN = atoi(str.c_str()); getline(inFile, books[size].Title);    getline(inFile, books[size].Author); getline(inFile, books[size].publisher);          getline(inFile,...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT